json - 如何让 Spark 将 JSON 转义字符串字段解析为 JSON 对象以推断数据帧中的

我有一组文件作为输入,每行格式化为一个 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/

相关文章:

python - Pandas 两行具有相同的索引,如何更改它们

mongodb - 使用 mongo shell 更改 mongodb 中的文档结构

php - Controller 中的 Codeigniter 负载模型

c# - 如何在 MVC 5 中下拉(多选)框

c# - 门面模式中的门面类是否需要是静态的?

r - 如何将字符串解析为真正的等式

angular-material - 如何更改 Angular Material datepicke

angular - PrimeNG 不适用于 angular2 cli?

r - 在 R 中转换日期格式

r - 获取r中具有最大日期的所有相应行