Spark 中如何将DataFrame JSON字符串列转换为Array与Struct类型
实现方案
因为name列存储的是序列化后的JSON字符串,直接对列做类型强转无法解析JSON内容,所有值会变为null,必须通过JSON解析逻辑匹配自定义结构,完整操作流程如下:
1. 定义匹配目标结构的自定义Schema
按照你给出的预期结构,先把name列对应的嵌套类型明确定义出来:
from pyspark.sql.types import StructType, StructField, ArrayType, StringType from pyspark.sql.functions import col # 与预期schema完全对齐的name列结构定义 name_target_schema = ArrayType( StructType([ StructField("extension", ArrayType( StructType([ StructField("url", StringType(), nullable=True), StructField("valueMetadata", StructType(), nullable=True), StructField("modifiedDateTime", StringType(), nullable=True), StructField("code", StringType(), nullable=True) ]) ), nullable=True), StructField("lastName", StringType(), nullable=True), StructField("firstName", ArrayType(StringType(), containsNull=True), nullable=True) ]) )
2. 解析原字符串列并替换列类型
使用from_json函数读取原字符串列的JSON内容,按照定义的Schema转成结构化类型,替换原来的字符串列:
from pyspark.sql.functions import from_json df_processed = df.withColumn( "name", from_json(col("name"), name_target_schema) )
3. 校验结果Schema
执行df_processed.printSchema(),输出结构会和你预期的schema完全一致,后续可以直接对name列执行explode操作展开多行。
常见坑点
- 严禁直接对字符串列做
.cast()类型转换:Spark不会自动识别字符串里的JSON格式,强转后的列会全量为null - 如果原JSON存在和定义Schema不匹配的字段,可在
from_json中传入解析选项做兼容,比如from_json(col("name"), name_target_schema, {"ignoreNullFields": "false"}) - 定义Schema时要和预期的可空性保持一致,避免后续explode、取嵌套字段的时候出现类型不匹配的报错
内容的提问来源于stack exchange,提问作者Rex
相关产品推荐
相关产品推荐

