luc*_*ucy -2 json scala apache-spark apache-spark-sql
我有一个数据框,它是带有 json 字符串的 json 列。下面的例子。有 3 列 - a、b、c。列 c 是 stringType
| a | b | c |
--------------------------------------------------------
|77 |ABC | {"12549":38,"333513":39} |
|78 |ABC | {"12540":38,"333513":39} |
Run Code Online (Sandbox Code Playgroud)
我想让它们成为数据框的列(枢轴)。下面的例子 -
| a | b | 12549 | 333513 | 12540
---------------------------------------------
|77 |ABC |38 |39 | null
|77 |ABC | null |39 | 38
Run Code Online (Sandbox Code Playgroud)
这可能不是最有效的,因为它必须json额外读取所有记录以推断模式。如果您可以静态定义架构,它应该做得更好。
val data = spark.createDataset(Seq(
(77, "ABC", "{\"12549\":38,\"333513\":39}"),
(78, "ABC", "{\"12540\":38,\"333513\":39}")
)).toDF("a", "b", "c")
val schema = spark.read.json(data.select("c").as[String]).schema
data.select($"a", $"b", from_json($"c", schema).as("s")).select("a", "b", "s.*").show(false)
Run Code Online (Sandbox Code Playgroud)
结果:
+---+---+-----+-----+------+
|a |b |12540|12549|333513|
+---+---+-----+-----+------+
|77 |ABC|null |38 |39 |
|78 |ABC|38 |null |39 |
+---+---+-----+-----+------+
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6668 次 |
| 最近记录: |