How to store JSON dataframe with comma sepearted

ぐ巨炮叔叔 提交于 2020-05-17 08:46:18

问题


I need to write record of dataframe to a json file. If I write the dataframe into the file it stores like {"a":1} {"b":2}, I want to write the dataframe like this [{"a":1} ,{"b":2}]. Can you please help me. Thanks in advance.


回答1:


Use to_json function to create array of json objects then use .saveAsTextFile to save the json object.

Example:

#sample dataframe
df=spark.createDataFrame([("a",1),("b",2)],["id","name"])

from pyspark.sql.functions import *

df.groupBy(lit("1")).\
agg(collect_list(struct(*[df.columns])).alias("cl")).\
select(to_json("cl").alias("jsn")).\
rdd.\
map(lambda x:x["jsn"]).\
saveAsTextFile("<path>")

cat <path>
#[{"id":"a","name":1},{"id":"b","name":2}]


来源:https://stackoverflow.com/questions/61420933/how-to-store-json-dataframe-with-comma-sepearted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!