问题
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