如何使用Spark读取数据帧中的JSON字符串文件

时间:2019-04-10 11:28:39

标签: scala apache-spark apache-spark-sql spark-streaming

我有一些示例文件,该文件中包含json字符串,如何在spark中处理这种类型的文件。

样本文件

{"Id":"240","Page":"dashboard","test":"working"}
{"Amt": "0.0","deliveryfee": "Free","ProductList": "{{ProductId=1,Price=200,Quantity=1},{ProductId=2,Price=600,Quantity=1}}","sample": "data"}

以json格式读取文件

val data = spark.read.option("multiLine", "true").json("/data/test/test.json")

df.printSchema
root
 |-- Amt: string (nullable = true)
 |-- ProductList: string (nullable = true)
 |-- deliveryfee: string (nullable = true)
 |-- sample: string (nullable = true)

printSchema将 ProductList 显示为字符串,但不是。

1 个答案:

答案 0 :(得分:1)

您可能想要这样的东西:

{
"Amt": "0.0",
"deliveryfee": "Free",
"ProductList": [{
    "ProductId": 1,
    "Price": 200,
    "Quantity": 1
}, {
    "ProductId": 2,
    "Price": 600,
    "Quantity": 1
}],
"sample": "data"

} 编辑:关键是该字段中的JSON是字符串的方式,您需要更改JSON或将该字段作为字符串使用