首页 > 解决方案 > Spark 将 Json 数组转换为结构体数组

问题描述

我正在寻找将 JSON 字符串数组转换为结构数组的方法。

样本数据:

{
  "col1": "col1Value",
  "col2":[
    "{\"SubCol1\":\"ABCD\",\"SubCol2\":\"EFGH\"}",
    "{\"SubCol1\":\"IJKL\",\"SubCol2\":\"MNOP\"}"
  ]
}

数据集架构:

StructType(StructField(col1,StringType,true), StructField(col2,ArrayType(StringType,true),true))

预期输出:

{
  "col1": "col1Value",
  "col2":[
    {"SubCol1":"ABCD","SubCol2":"EFGH"},
    {"SubCol1":"IJKL","SubCol2":"MNOP"}
  ]
}

预期架构:

StructType(StructField(col1,StringType,true), StructField(col2,ArrayType(StructType(StructField(SubCol1,StringType,true), StructField(SubCol2,StringType,true)),true),true))

我试过df.withColumn("col2", from_json($"col2", new_schema))了,但这给了我错误:

org.apache.spark.sql.AnalysisException:由于数据类型不匹配,无法解析 'jsontostructs(`col2`)':参数 1 需要字符串类型,但是,'`col2`' 是数组类型。

标签: jsonscaladataframeapache-sparkapache-spark-sql

解决方案


您可以col2先转换为字符串类型:

val df2 = df.withColumn("col2", 
    from_json(
        $"col2".cast("string"), 
        lit("array<struct<SubCol1:string, SubCol2:string>>")
        // or use new_schema as in your code
    )
)

推荐阅读