【问题标题】:How to parse rows of a small DataFrame as json strings?如何将小 DataFrame 的行解析为 json 字符串?
【发布时间】:2018-01-26 17:00:21
【问题描述】:

我有一个 DataFrame df 是一些预处理的结果。 df 的大小约为 10,000 行。 我将这个 DataFrame 保存在 CSV 中,如下所示: df.coalesce(1).write.option("sep",";").option("header","true").csv("output/path")

现在我想将此 DataFrame 保存为 txt 文件,其中 row 是 JSON 字符串。因此,列名应该传递给 JSON 字符串中的属性。

例如:

df =
  col1   col2   col3
  aa     34     55
  bb     13     77

json_txt =
{"col1": "aa", "col2": "34", "col3": "55"}
{"col1": "bb", "col2": "13", "col3": "77"}

最好的方法是什么?

【问题讨论】:

  • 你可以使用 df.write.json(输出路径)
  • see this 代替 .toDF() 使用 .createDataFrame()
  • @RameshMaharjan:它会像我展示的那样写每一行吗?
  • 当然可以。尝试一下,测试一下,如果失败了,请告诉我
  • @RameshMaharjan:让我测试一下,看看我是否得到了我想要的东西,只需使用df.coalesce(1).write.json("path")

标签: json scala apache-spark


【解决方案1】:

您可以使用write.json api 将dataframejson 格式保存为

df.coalesce(1).write.json("output path of json file")

上面的代码会创建一个 json 文件。但是如果你想要 text 格式(json text)那么你可以使用toJSON api as

df.toJSON.rdd.coalesce(1).saveAsTextFile("output path to text file")

希望回答对你有帮助

【讨论】:

    猜你喜欢
    • 2021-06-28
    • 2020-02-28
    • 1970-01-01
    • 2011-03-14
    • 2018-06-22
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多