【发布时间】:2021-04-01 17:10:49
【问题描述】:
我一直在尝试用 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.getResource 读取它时,scala 给了我错误,而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)
【问题讨论】:
标签: json scala apache-spark spark-shell jsonlines