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

Spark读取嵌套JSON:如何将嵌套字段展开为DataFrame独立列

如何将Spark DataFrame中的嵌套place字段展开为独立列?

你当前的代码读取JSON后,嵌套的place字段会作为一个结构体列存在,要把它的子字段拆分为独立列,只需在读取数据后通过Spark的列操作展开嵌套结构体即可。

输入JSON示例

{"place":{"place_name":"NYC","lon":0,"lat":0,"place_id":1009}, "region":{"region_issues":[{"key":"health","issue_name":"Cancer"},{"key":"sports","issue_name":"swimming"}]}}

现有代码

val schemaRsvp =  new StructType()
      .add("place",  StructType(Array(
      StructField("place_name", DataTypes.StringType),
      StructField("lon", DataTypes.IntegerType),
      StructField("lat", DataTypes.IntegerType),
      StructField("place_id", DataTypes.IntegerType))))

val ip =  spark.read.schema(schemaRsvp).json("D:\\Data\\rsvp\\inputrsvp.json")
ip.show()

解决方案

读取数据后,使用select方法配合col("place.*")可以一次性展开嵌套结构体的所有子字段为独立列,若需要保留其他字段也可一并指定。修改后的完整代码如下:

import org.apache.spark.sql.functions.col
import org.apache.spark.sql.types.{ArrayType, StringType, StructField, StructType, DataTypes}

val schemaRsvp =  new StructType()
      .add("place",  StructType(Array(
      StructField("place_name", DataTypes.StringType),
      StructField("lon", DataTypes.IntegerType),
      StructField("lat", DataTypes.IntegerType),
      StructField("place_id", DataTypes.IntegerType))))
      // 可选:若需要保留region字段,补充对应的Schema定义
      .add("region", StructType(Array(
      StructField("region_issues", ArrayType(StructType(Array(
          StructField("key", StringType),
          StructField("issue_name", StringType)
      )))))))

val ip =  spark.read.schema(schemaRsvp).json("D:\\Data\\rsvp\\inputrsvp.json")

// 仅展开place字段的所有子列
val expandedIp = ip.select(col("place.*"))
expandedIp.show()

执行后输出

+----------+---+---+--------+
|place_name|lon|lat|place_id|
+----------+---+---+--------+
|       NYC|  0|  0|    1009|
+----------+---+---+--------+

如果需要同时保留region字段,可修改select语句为:

val expandedIp = ip.select(col("place.*"), col("region"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 12:25:23