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

Databricks PySpark中是否有类似AWS Glue Unbox类的JSON转Struct功能?

在Databricks PySpark DataFrame中将JSON字符串转换为Struct类型

在PySpark中,你可以使用from_json函数实现类似AWS Glue Dynamic Frame中Unbox的功能,将字符串格式的JSON数据转换为Struct类型。以下是具体实现步骤:

1. 定义目标Struct类型

首先需要明确JSON字符串对应的结构化Schema,有两种定义方式:

  • 使用StructType显式定义:适合复杂嵌套结构
  • 使用DDL字符串定义:适合简单结构,写法更简洁

示例:假设你的JSON字符串格式为{"name": "张三", "age": 28, "contact": {"phone": "138xxxxxxx", "email": "zhangsan@example.com"}}

from pyspark.sql import functions as F
from pyspark.sql.types import StructType, StructField, StringType, IntegerType

# 方式1:StructType定义
target_schema = StructType([
    StructField("name", StringType(), nullable=True),
    StructField("age", IntegerType(), nullable=True),
    StructField("contact", StructType([
        StructField("phone", StringType(), nullable=True),
        StructField("email", StringType(), nullable=True)
    ]))
])

# 方式2:DDL字符串定义
target_schema = "name string, age int, contact struct<phone:string, email:string>"

2. 执行JSON转Struct转换

使用from_json函数将目标列的JSON字符串解析为Struct类型:

# 假设原DataFrame名为df,存储JSON字符串的列名为json_str
df_transformed = df.withColumn("parsed_struct", F.from_json(F.col("json_str"), target_schema))

3. 可选:展开Struct字段(按需使用)

如果需要将Struct中的嵌套字段直接提取为DataFrame的列,可以用select展开:

# 展开所有Struct字段,并保留原列
df_expanded = df_transformed.select("*", "parsed_struct.*").drop("parsed_struct")

from_json函数会自动校验JSON字符串与目标Schema的匹配性,不匹配的字段会被置为null(可通过options参数调整校验行为),完全等效于Glue中Unbox类的解析能力。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 01:01:12