You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pyspark from_json解析JSON列全返回Null问题求助

PySpark解析JSON数组字段返回Null的问题解决

问题场景

环境:Python 3.7.12、PySpark 2.4.0
从原始字段提取出的data列是JSON数组格式的字符串(示例值为包含多个对象的数组),尝试用get_json_object(col("data"), "$.zip")提取字段返回Null;用StructType定义Schema后通过from_json解析,所有字段也全为Null。

核心原因

  1. get_json_object失效:data列是JSON数组(外层带[]),$.zip是针对单个JSON对象的路径,直接用这个路径无法匹配数组中的元素,所以返回Null。
  2. from_json Schema错误:定义的Schema是单个StructType,但实际数据是JSON数组,类型不匹配导致解析失败,所有字段返回Null。

解决方案

1. 正确使用get_json_object提取数组元素

要指定数组索引定位元素,比如提取第一个元素的zip:

test = df.select(
    col("id"), 
    get_json_object(col("data"), "$[0].zip").alias("zip")
).show(truncate=False)

如果要提取所有元素的字段,需先展开数组:

from pyspark.sql.functions import explode, from_json
from pyspark.sql.types import ArrayType, StructType, StructField, StringType

item_schema = StructType([
    StructField('zip', StringType(), True),
    StructField('phnumber', StringType(), True),
    StructField('name', StringType(), True)
])

df_with_array = df.withColumn("data_array", from_json("data", ArrayType(item_schema)))
df_exploded = df_with_array.select(col('id'), explode(col('data_array')).alias('item'))
df_exploded.select(col('id'), col('item.zip')).show()

2. 修正Schema后用from_json完整解析

将Schema定义为ArrayType包裹单个对象的StructType,再解析:

# 定义单个JSON对象的Schema
item_schema = StructType([
    StructField('zip', StringType(), True),
    StructField('phnumber', StringType(), True),
    StructField('name', StringType(), True),
    StructField('time', ArrayType(StringType()), True),
    StructField('history', ArrayType(StringType()), True)
])

# 外层是数组,整体Schema为ArrayType
schema = ArrayType(item_schema)

# 解析JSON数组列
data_json = df.withColumn("data", from_json("data", schema))

# 展开数组,获取每个对象的字段
result = data_json.select(
    col('id'), 
    explode(col('data')).alias('data_item')
).select(col('id'), col('data_item.*'))

result.show()

3. 保留数组结构的解析方式

如果不需要展开数组,解析后可直接访问数组内的字段集合:

data_json = df.withColumn("data", from_json("data", schema))
data_json.select('id', 'data.zip', 'data.phnumber').show()

内容的提问来源于stack exchange,提问作者gfgd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 05:05:18