如何在PySpark DataFrame中解析包含列表的JSON字符串?
解析PySpark DataFrame中的JSON字符串列(含嵌套数组)
针对你需要解析detailscolumn列(存储单个JSON字符串,包含Students数组)的需求,以下是具体实现步骤:
步骤1:定义JSON对应的Schema
首先明确JSON的层级结构,定义匹配的PySpark Schema,确保能准确解析嵌套数组与结构体:
from pyspark.sql.types import StructType, StructField, StringType, LongType, IntegerType, ArrayType # 定义"More Details"子结构体的Schema more_details_schema = StructType([ StructField("rolenum", StringType(), nullable=True), StructField("name", StringType(), nullable=True), StructField("joiningdate", StringType(), nullable=True) ]) # 定义"Details"子结构体的Schema details_schema = StructType([ StructField("refnumber", IntegerType(), nullable=True), StructField("refcolumn", IntegerType(), nullable=True) ]) # 定义单个Student元素的Schema student_schema = StructType([ StructField("city", StringType(), nullable=True), StructField("code", StringType(), nullable=True), StructField("Details", details_schema, nullable=True), StructField("More Details", more_details_schema, nullable=True) # 注意原JSON中的空格数量 ]) # 定义顶层JSON的Schema top_level_schema = StructType([ StructField("licence", StringType(), nullable=True), StructField("date", LongType(), nullable=True), StructField("Students", ArrayType(student_schema), nullable=True) ])
步骤2:解析JSON字符串为结构化数据
使用from_json函数将字符串列转换为PySpark结构体类型:
from pyspark.sql.functions import from_json, explode, col # 解析JSON列 parsed_df = df.withColumn("parsed_json", from_json(col("detailscolumn"), top_level_schema))
步骤3:展开Students数组
用explode函数将数组类型的Students展开为多行,每个学生条目单独占一行:
exploded_df = parsed_df.withColumn("student", explode(col("parsed_json.Students")))
步骤4:提取嵌套结构体字段为单独列
将嵌套的Details和More Details中的字段提取为独立列,带空格的字段名需用反引号包裹:
final_df = exploded_df.select( col("parsed_json.licence"), col("parsed_json.date"), col("student.city"), col("student.code"), col("student.Details.refnumber").alias("refnumber"), col("student.Details.refcolumn").alias("refcolumn"), col("student.`More Details`.rolenum").alias("rolenum"), col("student.`More Details`.name").alias("name"), col("student.`More Details`.joiningdate").alias("joiningdate") )
最终结果说明
执行后final_df会生成以下结构化列:
licence: 原JSON中的版本号date: 时间戳city: 学生所在城市code: 学生编码(允许为null)refnumber: Details中的参考编号refcolumn: Details中的参考列号rolenum: More Details中的学号name: 学生姓名(允许为null)joiningdate: 入学日期(允许为null)
内容的提问来源于stack exchange,提问作者Sankara Rao
相关产品推荐
相关产品推荐

