如何用逗号分隔存储 JSON 数据框 [英] How to store JSON dataframe with comma sepearted

查看:24
本文介绍了如何用逗号分隔存储 JSON 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将数据帧的记录写入 json 文件.如果我将数据帧写入它存储的文件中,例如 {"a":1} {"b":2},我想像这样编写数据帧 [{"a":1} ,{"b":2}].你能帮我么.提前致谢.

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.

推荐答案

使用 to_json 函数创建json 对象数组 然后使用 .saveAsTextFile 保存 json 对象.

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

示例:

#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}]

这篇关于如何用逗号分隔存储 JSON 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆