首页 > 解决方案 > 无法使用 spark 从多行 json 字符串或 JSONL 字符串创建数据帧

问题描述

我一直在尝试用 jsonl 字符串形成数据框。我能够形成数据框,但问题是只读取单行,忽略其他行。
这是我在 spark-shell 中尝试的东西

// This one is example multiline json.
val jsonEx = "{\"name\":\"James\"}{\"name\":\"John\"}{\"name\":\"Jane\"}"

// schema for it is 
val sch = new StructType().add("name", StringType)

val ds = Seq(jsonEx).toDS()

// 1st attempt -- using multiline and spark.json
spark.read.option("multiLine", true).schema(sch).json(ds).show
+-----+
| name|
+-----+
|James|
+-----+

// 2nd attempt -- using from_json
ds.withColumn("json", from_json(col("value"), sch)).select("json.*").show
+-----+
| name|
+-----+
|James|
+-----+

//3rd attempt -- using from_json in little different way
ds.select(from_json(col("value"), sch) as "json").select("json.*").show
+-----+
| name|
+-----+
|James|
+-----+

I even tried updating string as, 
 val jsonEx = "{\"name\":\"James\"}\n{\"name\":\"John\"}\n{\"name\":\"Jane\"}"
and 
val jsonEx = "{\"name\":\"James\"}\n\r{\"name\":\"John\"}\n\r{\"name\":\"Jane\"}"

But the result was same.

有人在这里想念什么吗?

如果有人想知道为什么我不从文件而不是字符串中读取。resources我在路径中有一个 jsonl 配置文件。当我尝试使用getClass.getResourcescala 读取它时,我在getClass.getResourceAsStream工作时出错,我能够读取数据。

val configPath = "/com/org/example/data_sources_config.jsonl"
for(line <- Source.fromInputStream(getClass.getResourceAsStream(configPath)).getLines) { print(line)}
{"name":"james"} ...

but when I do, 
for(line <- Source.fromFile(getClass.getResource(configPath).getPath).getLines) { print(line)}
java.io.FileNotFoundException: file:/Users/sachindoiphode/workspace/dap-links-datalake-jobs/target/dap-links-datalake-jobs-0.0.65.jar!/com/org/example/data_sources_config.jsonl (No such file or directory)

标签: jsonscalaapache-sparkspark-shelljsonlines

解决方案


即使jsonEx是多行 JSON。它仍然是一个元素。您需要从中提取行。

val ds = jsonEx.split("\n").toSeq.toDS

要读取多行 JSON 文件,您可以尝试以下操作:

val path = "/com/org/example/data_sources_config.jsonl"
val source = Source.fromFile(getClass.getResource(path).getPath)
val content = source.getLines.mkString

如果content.split().toSq.toDF要从中创建数据框,请执行此操作。


推荐阅读