为了账号安全,请及时绑定邮箱和手机立即绑定

从 Pyspark Dataframe 创建 Json 结构

从 Pyspark Dataframe 创建 Json 结构

拉莫斯之舞 2023-09-26 14:11:19
我有数据框,它是左连接的产物。现在我想创建 json 结构。我尝试使用不同的选项,但无法创建它。这是我的数据框:col1    col2    col3    col41111    name    aaa     bbb1111    name    ccc     ddd1111    name    iii     kkk1112    name1   abcd    def1112    name1   DEFG    ABXC所需的 json 结构是:{col1: 1111, col2: name, details: [{col3: aaa, col4: bbb}, {col3: ccc, col4: ddd}, {col3: iii, col4: kkk}]},{col1: 1112, col2: name1, details: [{col3: abcd, col4: def}, {col3: DEFG, col4: ABXC}]}Python
查看完整描述

1 回答

?
慕斯709654

TA贡献1840条经验 获得超5个赞

你可以这样做:


import pyspark.sql.functions as f


df = df.withColumn("details", f.to_json(f.struct("col3", "col4")))

df = df.groupBy(*["col1", "col2"]).agg(f.collect_list("details").alias("details"))


df.write.format('json').save('/path/file_name.json')


查看完整回答
反对 回复 2023-09-26
  • 1 回答
  • 0 关注
  • 59 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信