json - 无法使用 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.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)
解决方案
即使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
要从中创建数据框,请执行此操作。
推荐阅读
- python - django.contrib.gis.geos 抛出段错误
- c# - 相当于 Dart 中的 C##region?
- linux - 找不到包'libxml++-2.6'
- powershell - 仅限Powershell:根据映射文件更改文件名,然后复制到另一个目录
- python - ssh-python 的构建轮子失败
- wordpress - 如何在单个帖子页面上显示自定义 texonomy 的类别相关帖子
- sql - 删除或更改 ETL 中的记录
- excel - “我们发现 Excel 中的某些内容存在问题”公式的问题
- javascript - 如何在嵌入后立即发送消息?
- sql-server - SQL如何从xml字符串中提取值