gpt4 book ai didi

json - 解析 Spark Streaming SQL 中的嵌套 JSON 字符串化列

转载 作者:行者123 更新时间:2023-12-01 22:40:38 62 4
gpt4 key购买 nike

我遵循了 Spark Streaming 指南,并能够使用 sqlContext.read.json(rdd) 获取 json 数据的 sql 上下文。问题是其中一个 json 字段本身就是我想要解析的 JSON 字符串。

有没有办法在 Spark sql 中完成此任务,或者使用 ObjectMapper 解析字符串并连接到其余数据会更容易吗?

澄清一下,JSON 的值之一是一个包含 JSON 数据且内部引号已转义的字符串。我正在寻找一种方法来告诉解析器将该值视为字符串化的 JSON

Json 示例

{ 
"key": "val",
"jsonString": "{ \"too\": \"bad\" }",
"jsonObj": { "ok": "great" }
}

SQLContext 如何解析它

root
|-- key: string (nullable = true)
|-- jsonString: string (nullable = true)
|-- jsonObj: struct (nullable = true)
| |-- ok: string (nullable = true)

我多么想要它

root
|-- key: string (nullable = true)
|-- jsonString: struct (nullable = true)
| |-- too: string (nullable = true)
|-- jsonObj: struct (nullable = true)
| |-- ok: string (nullable = true)

最佳答案

您可以使用from_json函数来解析DataSet的列:

import org.apache.spark.sql.functions._
import org.apache.spark.sql.types._

val stringified = spark.createDataset(Seq("{ \"too\": \"bad\" }", "{ \"too\": \"sad\" }"))
stringified.printSchema()

val structified = stringified.withColumn("value", from_json($"value", StructType(Seq(StructField("too", StringType, false)))))
structified.printSchema()

它将value列从string转换为struct:

root
|-- value: string (nullable = true)

root
|-- value: struct (nullable = true)
| |-- too: string (nullable = false)

关于json - 解析 Spark Streaming SQL 中的嵌套 JSON 字符串化列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34601839/

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