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

查看:123
本文介绍了如何存储逗号分隔的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 函数创建array of json objects,然后使用 .saveAsTextFile 保存json对象.

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

Example:

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

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

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