从 Pyspark Dataframe 创建 Json 结构

我有数据框,它是左连接的产物。现在我想创建 json 结构。


我尝试使用不同的选项,但无法创建它。这是我的数据框:


col1    col2    col3    col4

1111    name    aaa     bbb

1111    name    ccc     ddd

1111    name    iii     kkk

1112    name1   abcd    def

1112    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


拉莫斯之舞
浏览 60回答 1
1回答

慕斯709654

你可以这样做:import pyspark.sql.functions as fdf = 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')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python