我有一组文件作为输入,每行格式化为一个 JSON 对象。然而,问题在于这些 JSON 对象的一个字段是 JSON 转义字符串。示例
{
"id":1,
"name":"some name",
"problem_field": "{\"height\":180,\"weight\":80,}",
}
预计,当使用 sqlContext.read.json
时,它将创建一个具有 3 列 id、name 和 problem_field 的 DataFrame,其中 problem_field 是一个字符串。
我无法控制输入文件,我希望能够在 Spark 中解决这个问题,所以,有什么方法可以让 Spark 将该字符串字段读取为 JSON 并正确推断其模式?
注意:上面的 json 只是一个玩具示例,在我的例子中,problem_field 将具有可变的不同字段,Spark 推断这些字段非常好,而我不必对存在哪些字段做出任何假设。
最佳答案
这是可以接受的解决方案吗?
val sc: SparkContext = ...
val sqlContext = new SQLContext(sc)
val escapedJsons: RDD[String] = sc.parallelize(Seq("""{"id":1,"name":"some name","problem_field":"{\"height\":180,\"weight\":80}"}"""))
val unescapedJsons: RDD[String] = escapedJsons.map(_.replace("\"{", "{").replace("\"}", "}").replace("\\\"", "\""))
val dfJsons: DataFrame = sqlContext.read.json(unescapedJsons)
dfJsons.printSchema()
// Output
root
|-- id: long (nullable = true)
|-- name: string (nullable = true)
|-- problem_field: struct (nullable = true)
| |-- height: long (nullable = true)
| |-- weight: long (nullable = true)
关于json - 如何让 Spark 将 JSON 转义字符串字段解析为 JSON 对象以推断数据帧中的正确结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37225414/