如何在Spark数据帧中分解字符串



我有一个JSON字符串,它实际上是一个数组

|{"[0].id":"cccccccc","[0].label":"xxxxxx","[0].deviceTypeId":"xxxxxxxxxxxx"}|

我需要把它分解,这样我就可以把所有的键都作为列,就像这个一样

dataFrame.
.withColumn("single", explode_outer(col("nested")))

然而,spark一直抱怨explode应该映射一个数组。

我该怎么做?

您可以使用from_json将JSON字符串解析为MapType,然后分解映射和pivot:

val df = Seq(
(1,"""{"[0].id":"cccccccc","[0].label":"xxxxxx","[0].deviceTypeId":"xxxxxxxxxxxx"}""")
).toDF("id", "nested")
val df1 = (df
.select(
col("id"),
explode(from_json(col("nested"), lit("map<string,string>")))
)
.groupBy("id")
.pivot("key")
.agg(first(col("value"))))
df1.show
//+---+----------------+--------+---------+
//| id|[0].deviceTypeId|  [0].id|[0].label|
//+---+----------------+--------+---------+
//|  1|    xxxxxxxxxxxx|cccccccc|   xxxxxx|
//+---+----------------+--------+---------+

最新更新