【发布时间】:2021-11-03 12:01:09
【问题描述】:
我想使用 Spark scala 从字符串格式的复杂 JSON 创建数据帧。
Spark 版本是 3.1.2。 Scala 版本是 2.12.14。
源数据如下:
{
"info": [
{
"done": "time",
"id": 9,
"type": "normal",
"pid": 202020,
"add": {
"fields": true,
"stat": "not sure"
}
},
{
"done": "time",
"id": 14,
"type": "normal",
"pid": 764310,
"add": {
"fields": true,
"stat": "sure"
}
},
{
"done": "time",
"id": 9,
"type": "normal",
"pid": 202020,
"add": {
"note": {
"id": 922,
"score": 0
}
}
}
],
"more": {
"a": "ok",
"b": "fine",
"c": 3
}
}
我尝试了以下操作,但没有工作。
val schema = new StructType().add("info", ArrayType(StringType)).add("more", StringType)
val rdd = ss.sparkContext.parallelize(Seq(Row(data))) // data is as mentioned above JSON
val df = ss.createDataFrame(rdd, schema)
df.printSchema()
模式打印如下
root
|-- info: array (nullable = true)
| |-- element: string (containsNull = true)
|-- more: string (nullable = true)
print(df.head())
Above line throws exception java.lang.RuntimeException: Error while encoding: java.lang.RuntimeException: java.lang.String is not a valid external type for schema of array<string>
请帮我做这件事。
【问题讨论】:
-
嗨,欢迎来到堆栈溢出,请阅读this。问题中缺少的主要内容是您到目前为止尝试了什么?因为通过谷歌搜索可以找到关于这个场景的数百万个教程。
标签: json scala dataframe apache-spark apache-spark-sql