【发布时间】:2021-08-09 21:28:28
【问题描述】:
我正在寻找将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`' 是数组类型。
【问题讨论】:
标签: json scala dataframe apache-spark apache-spark-sql