在 PySpark 中使用动态键展平嵌套 JSON 结构

Rob*_*dey 0 json apache-spark apache-spark-sql pyspark databricks

我正在尝试使用PySpark处理包含带有动态键的结构列的 json 文件。

结构列的架构如下所示:

{
  "UUID_KEY": {
     "time": STRING
     "amount": INTEGER
  }
}
Run Code Online (Sandbox Code Playgroud)

数据如下:

ID json_列
1 “{1:{金额:1,时间:2},2:{金额:10,时间:5}}”
2 “{3:{金额:1,时间:2},4:{金额:10,时间:5}”

目前,我将结构列作为字符串,因为通过指定/推断模式加载 JSON 不起作用因为第一层的键是随机生成的,并且数据太多。第二层始终相同,它包含amounttime

有没有办法在不知道第一层的键的情况下将此 JSON 字符串平铺到amount和列中?time

Ron*_*ain 6

这会起作用:

map_schema=MapType(StringType(), StructType([\
    StructField('amount', StringType(), True),\
    StructField('time', StringType(),True)\
]));

df\
.withColumn("json_column", F.from_json(F.col("json_column"), map_schema, {"allowUnquotedFieldNames":"true"}))\
.select("*", F.explode("json_column").alias("key", "value"))\
.select("id", "value.*")\
.show(truncate=False)
Run Code Online (Sandbox Code Playgroud)

输入:

+---+---------------------------------------------------+
|id |json_column                                        |
+---+---------------------------------------------------+
|1  |{1: {amount: 1, time: 2}, 2: {amount: 10, time: 5}}|
|2  |{3: {amount: 1, time: 2}, 4: {amount: 10, time: 5}}|
+---+---------------------------------------------------+

root
 |-- id: long (nullable = true)
 |-- json_column: string (nullable = true)
Run Code Online (Sandbox Code Playgroud)

输出:

+---+------+----+
|id |amount|time|
+---+------+----+
|1  |1     |2   |
|1  |10    |5   |
|2  |1     |2   |
|2  |10    |5   |
+---+------+----+
Run Code Online (Sandbox Code Playgroud)