简体   繁体   English

如何使用 pyspark 将数据帧转换为分配特定模式的 JSON 文件?

[英]How to convert a dataframe into a JSON file assigning a specific schema using pyspark?

I am using pyspark and i want to convert a spark dataframe into a specific file json.我正在使用 pyspark,我想将 spark 数据帧转换为特定的文件 json。 the Dataframe is like this:数据框是这样的:

| Key  | desc | value |
|:---- |:----:| -----:|
| 12345| type | AA    |
| 12345| id   | q1w2e3|
| 98765| type | BB    |
| 98765| id   | z1x2c3|

I need to convert it into a json like this:我需要将它转换成这样的 json:

{
  "12345": {
     "type":"AA,
     "id":"q1w2e3"
    },
  "98765":{
     "type":"BB",
     "id":"z1x2c3"
    }
}

Any idea?任何的想法? Thank you谢谢

First collect the dataframe首先收集数据框

Output = df.collect()

if you try to print the “Output” you will get List of Row Tuple something like this如果你尝试打印“输出”,你会得到这样的行元组列表

[Row(key:1234,desc:type,value:AA)…..] [行(键:1234,desc:类型,值:AA)......]

Now iterate over this list using for loop and Create dictionary and assign these value you can directly access them like this.现在使用 for 循环遍历此列表并创建字典并分配这些值,您可以像这样直接访问它们。

For row in Output:
     dict[key] = row[key]

once the dictionary is create then you can use Json.dumps(dict)创建字典后,您可以使用Json.dumps(dict)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 PySpark 将复杂的 JSON 转换为 dataframe? - How to convert complex JSON to dataframe by using PySpark? 如何使用pyspark读取文件并将其转换为数据帧? - How to read a file using pyspark and convert it to a dataframe? 使用 PySpark 将 JSON 文件读取为 Pyspark 数据帧? - Read JSON file as Pyspark Dataframe using PySpark? 使用 Pyspark 如何读取 JSON 文件并创建模式 - Using Pyspark how to read JSON file and create schema 如何使用 Pyspark 将多个 JSON 模式值附加到数据框下的单个列中 - How to append multiple JSON schema values into a single column under a dataframe using Pyspark 我想将 pyspark dataframe 转换为特定的 JSON 字符串 - I want to convert pyspark dataframe to specific JSON string Json 文件到 pyspark 数据框 - Json file to pyspark dataframe 使用 pyspark 中的 json 文件中的模式读取固定宽度文件 - Read fixed width file using schema from json file in pyspark 如何使用pyspark将具有多个可能值的Json数组列表转换为数据帧中的列 - How to convert Json array list with multiple possible values into columns in a dataframe using pyspark 如何使用推断模式读取列名中带点的 JSON 文件(Spark/Pyspark)? - How to read JSON file (Spark/Pyspark) with dots in column names using inferred schema?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM