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

Databricks中如何将DataFrame的JSON字符串列拆分为多列?

问题解决方法

你的错误来自两个核心问题:

  • 未正确定义Spark能识别的JSON Schema(你用了字符串列表,而非Spark的StructType结构)
  • 解析JSON后,字段是嵌套在EventPayload结构体中的,直接顶层选择字段会找不到

步骤1:定义正确的Spark Schema

根据你的JSON结构,需要用StructType和StructField明确每个字段的类型:

from pyspark.sql.types import StructType, StructField, IntegerType, StringType, TimestampType

EventPayloadSchema = StructType([
    StructField("Gcid", IntegerType(), True),
    StructField("CountryCode", StringType(), True),
    StructField("SubProgram", StringType(), True),
    StructField("Program", StringType(), True),
    StructField("Region", StringType(), True),
    StructField("AccountId", StringType(), True),
    StructField("CurrencyBalanceId", StringType(), True),
    StructField("BankAccountId", StringType(), True),
    StructField("CorrelationId", StringType(), True),
    StructField("Created", TimestampType(), True)
])

步骤2:解析JSON并提取嵌套字段

解析后,你需要通过点语法引用嵌套在EventPayload中的字段,或者直接展开整个结构体:

方法1:手动指定嵌套字段

df_filtered.withColumn("EventPayload", from_json("EventPayload", EventPayloadSchema))\
    .select(
        col("EventPayload.Gcid"),
        col("EventPayload.CountryCode"),
        col("EventPayload.SubProgram"),
        col("EventPayload.Program"),
        col("EventPayload.Region"),
        col("EventPayload.AccountId"),
        col("EventPayload.CurrencyBalanceId"),
        col("EventPayload.BankAccountId"),
        col("EventPayload.CorrelationId"),
        col("EventPayload.Created")
    )\
    .show()

方法2:快速展开所有嵌套字段(推荐)

如果要提取所有JSON中的字段,可以直接用EventPayload.*展开:

df_filtered.withColumn("EventPayload", from_json("EventPayload", EventPayloadSchema))\
    .select("EventPayload.*")\
    .show()

方法3:保留原DataFrame其他列 + 展开JSON字段

如果需要保留原表的其他列(比如EventTimestamp等),可以用*保留所有原列,再加上展开的JSON字段:

df_filtered.withColumn("EventPayload", from_json("EventPayload", EventPayloadSchema))\
    .select("*", "EventPayload.*")\
    .drop("EventPayload")  # 可选:删除原JSON字符串列
    .show()

错误原因说明

  • 你最初定义的EventPayloadSchema是字符串列表,Spark无法将其识别为JSON的结构描述,必须使用Spark官方的类型定义类。
  • 使用from_json后,EventPayload列从字符串类型变成了结构体类型,所有JSON字段都是该结构体的子字段,必须通过父列名.子字段名的方式引用,直接写子字段名会被视为顶层列,自然找不到。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 10:52:45