【问题标题】:Pyspark: How to convert a spark dataframe to json and save it as json file?Pyspark:如何将火花数据帧转换为 json 并将其保存为 json 文件?
【发布时间】:2019-04-24 20:52:30
【问题描述】:

我正在尝试将我的 pyspark sql 数据帧转换为 json,然后另存为文件。

df_final = df_final.union(join_df)

df_final 包含这样的值:

我尝试过这样的事情。但它创建了一个无效的 json。

df_final.coalesce(1).write.format('json').save(data_output_file+"createjson.json", overwrite=True)

{"Variable":"Col1","Min":"20","Max":"30"}
{"Variable":"Col2","Min":"25,"Max":"40"}

我预期的文件应该有如下数据:

[
{"Variable":"Col1",
"Min":"20",
"Max":"30"},
{"Variable":"Col2",
"Min":"25,
"Max":"40"}]

【问题讨论】:

  • 试试df.toJSON()

标签: python-3.x pyspark apache-spark-sql pyspark-sql


【解决方案1】:

以下是使用 PySpark 1.3+ 对数据帧执行相当于 json.dump 的方法。

df_list_of_jsons = df.toJSON().collect()
df_list_of_dicts = [json.loads(x) for x in df_list_of_jsons]
df_json = json.dumps(df_list_of_dicts)
sc.parallelize([df_json]).repartition(1).cache().saveAsTextFile("<HDFS_PATH>")

请注意,这会导致整个数据帧被加载到驱动程序内存中,因此仅建议对小数据帧进行此操作。

【讨论】:

    【解决方案2】:

    pyspark可以直接将dataframe存入json文件,无需将dataframe转成json。

    df_final.coalesce(1).write.format('json').save('/path/file_name.json')
    

    你仍然想将你的数据帧转换成 json 然后你可以使用 df_final.toJSON().

    【讨论】:

    • 是的,但是它逐行存储数据 {"Variable":"Col1","Min":"20","Max":"30"} {"Variable":"Col2" ,"Min":"25,"Max":"40"} 应该用 分隔,并用方括号括起来
    【解决方案3】:

    如果你想使用 spark 将结果处理为 json 文件,我认为你的输出模式在 hdfs 中是正确的。

    我假设您遇到了无法从普通 python 脚本中顺利读取数据的问题:

    with open('data.json') as f:
      data = json.load(f)
    

    你应该尝试逐行读取数据:

    data = []
    with open("data.json",'r') as datafile:
      for line in datafile:
        data.append(json.loads(line))
    

    您可以使用pandas 创建数据框:

    df = pd.DataFrame(data) 
    

    【讨论】:

    • 我试图理解为什么有一个与读取 json 文件而不是写出来有关的答案。我现在明白了,spark 写出的 json 格式不是逗号分隔的,因此必须以稍微不同的方式读回。非常感谢你
    • @FahadAshraf 很高兴有帮助。是的,spark 写出的 json 格式不是逗号分隔的。第一次读取从 spark(或其他 hdfs 模式)创建的 json 文件时非常混乱。
    【解决方案4】:

    解决方案可以使用collect,然后使用json.dump

    import json
    collected_df = df_final.collect()
    with open(data_output_file + 'createjson.json', 'w') as outfile:
        json.dump(data, outfile)
    

    【讨论】:

    • 其实这是正确的,但它不是直接在 hdfs 中创建文件。它在脚本运行的容器上创建
    • 使用驱动内存,不推荐使用。
    猜你喜欢
    • 2020-07-31
    • 2023-03-16
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 2020-10-30
    • 2018-02-22
    相关资源
    最近更新 更多