gpt4 book ai didi

scala - 如何从json字符串中提取值?

转载 作者:行者123 更新时间:2023-12-01 08:51:54 27 4
gpt4 key购买 nike

我有一个文件,其中包含一堆列和一个名为 jsonstring 的列是字符串类型,其中包含 json 字符串……假设格式如下:

{
"key1": "value1",
"key2": {
"level2key1": "level2value1",
"level2key2": "level2value2"
}
}

我想解析这个列是这样的: jsonstring.key1,jsonstring.key2.level2key1 to return value1, level2value1

我怎样才能在 Scala 或 Spark sql 中做到这一点。

最佳答案

使用 Spark 2.2,您可以使用函数 from_json它为你做 JSON 解析。

from_json(e: Column, schema: String, options: Map[String, String]): Column parses a column containing a JSON string into a StructType or ArrayType of StructTypes with the specified schema.



通过使用 * 支持展平嵌套列(star) 这似乎是最好的解决方案。
// the input dataset (just a single JSON blob)
val jsonstrings = Seq("""{
"key1": "value1",
"key2": {
"level2key1": "level2value1",
"level2key2": "level2value2"
}
}""").toDF("jsonstring")

// define the schema of JSON messages
import org.apache.spark.sql.types._
val key2schema = new StructType()
.add($"level2key1".string)
.add($"level2key2".string)
val schema = new StructType()
.add($"key1".string)
.add("key2", key2schema)
scala> schema.printTreeString
root
|-- key1: string (nullable = true)
|-- key2: struct (nullable = true)
| |-- level2key1: string (nullable = true)
| |-- level2key2: string (nullable = true)

val messages = jsonstrings
.select(from_json($"jsonstring", schema) as "json")
.select("json.*") // <-- flattening nested fields
scala> messages.show(truncate = false)
+------+---------------------------+
|key1 |key2 |
+------+---------------------------+
|value1|[level2value1,level2value2]|
+------+---------------------------+

scala> messages.select("key1", "key2.*").show(truncate = false)
+------+------------+------------+
|key1 |level2key1 |level2key2 |
+------+------------+------------+
|value1|level2value1|level2value2|
+------+------------+------------+

关于scala - 如何从json字符串中提取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39238367/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com