Sha*_*nda 7 python-3.x apache-spark-sql pyspark pyspark-sql
我正在尝试将我的 pyspark sql 数据帧转换为 json,然后另存为文件。
df_final = df_final.union(join_df)
Run Code Online (Sandbox Code Playgroud)
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"}
Run Code Online (Sandbox Code Playgroud)
我预期的文件应该有如下数据:
[
{"Variable":"Col1",
"Min":"20",
"Max":"30"},
{"Variable":"Col2",
"Min":"25,
"Max":"40"}]
Run Code Online (Sandbox Code Playgroud)
因为pyspark您可以直接将 dataframe 存储到 json 文件中,因此无需将 dataframe 转换为 json。
df_final.coalesce(1).write.format('json').save('/path/file_name.json')
Run Code Online (Sandbox Code Playgroud)
并且您仍然想将 datafram 转换为 json 然后您可以使用
df_final.toJSON().
解决方案可以使用collect然后使用json.dump:
import json
collected_df = df_final.collect()
with open(data_output_file + 'createjson.json', 'w') as outfile:
json.dump(data, outfile)
Run Code Online (Sandbox Code Playgroud)