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

将DataFrame中嵌套JSON字符串列转换为多列的实现方法

解决Spark DataFrame嵌套JSON字符串展开为多列的问题

嘿,针对你这个嵌套JSON列的展开需求,我给你整理了一个可行的Scala方案,用Spark内置的JSON解析工具就能搞定,步骤很清晰:

步骤1:导入必要的Spark SQL依赖包

首先得确保导入Spark SQL的类型定义包,这样才能准确匹配JSON的嵌套结构:

import org.apache.spark.sql.types.{StructType, StructField, ArrayType, IntegerType}
import org.apache.spark.sql.functions.{from_json, col}

步骤2:定义嵌套JSON对应的Schema

你的JSON是两层嵌套结构:外层key为-1,内层key也为-1,对应一个整数数组。我们需要用StructType来精准定义这个结构:

val jsonSchema = StructType(Seq(
  StructField("-1", StructType(Seq(
    StructField("-1", ArrayType(IntegerType))
  )))
))

步骤3:解析JSON字符串并展开为多列

先把column1的JSON字符串解析成结构化数据,再从数组中逐个提取元素作为独立列(这里假设你把数组6个元素命名为col_0到col_5):

val resultDf = df
  // 解析JSON字符串为结构化列
  .withColumn("parsed_json", from_json(col("column1"), jsonSchema))
  // 提取内层的整数数组
  .withColumn("data_array", col("parsed_json.-1.-1"))
  // 逐个提取数组元素生成独立列
  .withColumn("col_0", col("data_array").getItem(0))
  .withColumn("col_1", col("data_array").getItem(1))
  .withColumn("col_2", col("data_array").getItem(2))
  .withColumn("col_3", col("data_array").getItem(3))
  .withColumn("col_4", col("data_array").getItem(4))
  .withColumn("col_5", col("data_array").getItem(5))
  // 移除临时中间列(可选操作)
  .drop("column1", "parsed_json", "data_array")

查看处理后的最终结果

运行上述代码后,resultDf就会呈现你想要的多列结构:

+-----+-----+-----+-----+-----+-----+
|col_0|col_1|col_2|col_3|col_4|col_5|
+-----+-----+-----+-----+-----+-----+
| 7420|    0|   20|   22|    0|    0|
| 1006|    2|   18|   10|    0|    0|
| 6414|    0|   17|   11|    0|    0|
+-----+-----+-----+-----+-----+-----+

额外小提示

如果你的数组长度不固定,或者想更灵活处理,也可以用explode函数把数组拆分成行,但从你的示例来看,数组长度固定为6,直接提取每个元素是最高效的方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:06:55