gpt4 book ai didi

json - Spark from_json - StructType 和 ArrayType

转载 作者:行者123 更新时间:2023-12-04 18:26:03 54 4
gpt4 key购买 nike

我有一个以 XML 形式出现的数据集,其中一个节点包含 JSON。 Spark 将其作为 StringType 读取,因此我尝试使用 from_json() 将 JSON 转换为 DataFrame。

我能够转换一串 JSON,但如何编写架构以使用 Array?

没有数组的字符串 - 工作得很好

import org.apache.spark.sql.functions._

val schemaExample = new StructType()
.add("FirstName", StringType)
.add("Surname", StringType)

val dfExample = spark.sql("""select "{ \"FirstName\":\"Johnny\", \"Surname\":\"Boy\" }" as theJson""")

val dfICanWorkWith = dfExample.select(from_json($"theJson", schemaExample))

dfICanWorkWith.collect()

// Results \\
res19: Array[org.apache.spark.sql.Row] = Array([[Johnny,Boy]])

带数组的字符串 - 想不通
import org.apache.spark.sql.functions._

val schemaExample2 = new StructType()
.add("", ArrayType(new StructType()
.add("FirstName", StringType)
.add("Surname", StringType)
)
)

val dfExample2= spark.sql("""select "[{ \"FirstName\":\"Johnny\", \"Surname\":\"Boy\" }, { \"FirstName\":\"Franky\", \"Surname\":\"Man\" }" as theJson""")

val dfICanWorkWith = dfExample2.select(from_json($"theJson", schemaExample2))

dfICanWorkWith.collect()

// Result \\
res22: Array[org.apache.spark.sql.Row] = Array([null])

最佳答案

问题是您没有完全合格的 json。您的 json 缺少一些东西:

  • 首先,您缺少完成 json 的周围 {}
  • 其次,您缺少变量值(您将其设置为“”但未添加)
  • 最后你错过了结束]

  • 尝试将其替换为:
    val dfExample2= spark.sql("""select "{\"\":[{ \"FirstName\":\"Johnny\", \"Surname\":\"Boy\" }, { \"FirstName\":\"Franky\", \"Surname\":\"Man\" }]}" as theJson""")

    你会得到:
    scala> dfICanWorkWith.collect()
    res12: Array[org.apache.spark.sql.Row] = Array([[WrappedArray([Johnny,Boy], [Franky,Man])]])

    关于json - Spark from_json - StructType 和 ArrayType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45003393/

    54 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com