【问题标题】:Not able to create dataframe out of multi line json string or JSONL string using spark无法使用 spark 从多行 json 字符串或 JSONL 字符串创建数据帧
【发布时间】: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


    【解决方案1】:

    即使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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      • 2018-10-23
      • 1970-01-01
      • 2020-07-04
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      相关资源
      最近更新 更多