json - 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`' 是数组类型。
解决方案
您可以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
)
)
推荐阅读
- oracle - 带有选择语句的 BOUNDFILLER
- amazon-web-services - 在 linux 机器上安装 awsebcli 时出现安装错误
- mysql - 使用 group by 在两个表中获取最大值时遇到问题
- javascript - 与多个状态变量反应的通用函数
- python - LinkedIn API“空 oauth2 访问令牌”错误
- mysql - 使用 find_in_set 和 group_concat 的 SQL 极端案例问题
- php - 确定下一个演奏者
- mysql - 是否可以使用列值sql查询作为和条件
- python - 使用计数器后,Python循环没有中断
- python - 用 numpy 实现最大/平均池(有步幅)