如何在PySpark中将DataFrame的JSON对象数组列转为新表?
解决PySpark解析JSON对象数组为结构化表的问题
分两种场景处理:
场景1:你的列是字符串格式的JSON数组
如果json_array_col存的是字符串(比如你示例里的JSON文本),先解析成结构体数组,再展开:
- 定义JSON对象的Schema:
from pyspark.sql.types import StructType, StructField, StringType, BooleanType, IntegerType, ArrayType json_schema = StructType([ StructField("name", StringType(), nullable=True), StructField("apartment", StringType(), nullable=True), StructField("isitflag", BooleanType(), nullable=True), StructField("iscruxflag", BooleanType(), nullable=True), StructField("hisindexnum", IntegerType(), nullable=True), StructField("valueinb", StringType(), nullable=True) ])
- 解析字符串为数组,再展开成单行:
from pyspark.sql.functions import explode, from_json # 把字符串转成结构体数组 df_parsed = df.withColumn("json_struct_array", from_json(df.json_array_col, ArrayType(json_schema))) # 将数组展开,每个JSON对象对应一行 df_exploded = df_parsed.select(explode("json_struct_array").alias("json_data")) # 把结构体的字段展开为表的列 result_df = df_exploded.select("json_data.*")
场景2:你的列已经是Array[Struct]类型
如果列本身已经是结构化的数组(不是字符串),直接展开即可:
from pyspark.sql.functions import explode # 展开数组到单行 df_exploded = df.select(explode("json_array_col").alias("json_data")) # 展开结构体字段为列 result_df = df_exploded.select("json_data.*")
验证结果
运行result_df.show()就能得到目标结构化表:JSON的键作为列名,每个对象的对应值作为行数据。
内容的提问来源于stack exchange,提问作者winnervc
相关产品推荐
相关产品推荐

