【发布时间】:2019-12-14 23:33:24
【问题描述】:
我已经对此提出了一个问题,但那是针对Array type column。
最初认为该问题仅发生在 JSON 数组字段中,但看起来发生了这种情况
甚至是一个简单的标量字段。
下面是我正在加载的数据。
val ds = spark.read.textFile("./src/main/resources/json/jsonwithnullfield.txt").as[String]
ds.show(false)
+--------------------------------------------------------------------+
|value |
+--------------------------------------------------------------------+
|{"title": {"titleId": "111", "titleName": "AAA", "titleDesc": null}}|
|{"title": {"titleId": "222", "titleName": "BBB", "titleDesc": null}}|
|{"title": {"titleId": "333", "titleName": "CCC", "titleDesc": null}}|
|{"title": {"titleId": "444", "titleName": "DDD", "titleDesc": null}}|
|{"title": {"titleId": "555", "titleName": "EEE", "titleDesc": null}}|
+--------------------------------------------------------------------+
然后将 Dataset[String] 加载为 JSON
我看到了schema 中的所有列,包括titleDesc 字段。
val jsonDF = spark.read.json(ds)
jsonDF.printSchema()
jsonDF.show(false)
root
|-- title: struct (nullable = true)
| |-- titleDesc: string (nullable = true)
| |-- titleId: string (nullable = true)
| |-- titleName: string (nullable = true)
+------------+
|title |
+------------+
|[, 111, AAA]|
|[, 222, BBB]|
|[, 333, CCC]|
|[, 444, DDD]|
|[, 555, EEE]|
+------------+
然后我使用 to_json function 将 title 值转换为 JSON,但结果似乎没有按预期工作
因为我在 JSON 值中没有看到 titleDesc 字段。
jsonDF.select(to_json(struct($"title.*")).as("Title")).show(false)
输出:
+-----------------------------------+
|Title |
+-----------------------------------+
|{"titleId":"111","titleName":"AAA"}|
|{"titleId":"222","titleName":"BBB"}|
|{"titleId":"333","titleName":"CCC"}|
|{"titleId":"444","titleName":"DDD"}|
|{"titleId":"555","titleName":"EEE"}|
+-----------------------------------+
我想查看 JSON 输出字符串中的 titleDesc 字段。
如果无法通过to_json 函数处理,是否有解决方法?
【问题讨论】:
标签: json apache-spark apache-spark-sql