将具有嵌套数组的JSON转换为CSV [英] Converting a JSON with a nested array to CSV
问题描述
这是我的JSON模板:
Here is a template of my JSON:
{
"field 1": [
{
"id": "123456"
},
{
"about": "YESH"
},
{
"can_post": true
},
{
"category": "Community"
}
],
"field 2": [
{
"id": "123456"
},
{
"about": "YESH"
},
{
"can_post": true
},
{
"category": "Community"
}
]
}
我想使用Python将这种JSON转换为以下格式的CSV:
I would like to convert this JSON into a csv in the following format using Python:
0 field 1, id, about, can_post, category
1 field 2, id, about, can_post, category
我尝试使用熊猫先读取read_json,然后再读取to_csv,但这没有用.
I tried using pandas to read_json and then to_csv but it didn't work.
谢谢
推荐答案
import csv
import json
json.load(json_data)将json_data(json文档(txt/二进制文件))反序列化为python对象.
json.load( json_data) Deserialize the json_data ( json document(txt/ binary file)) to python object.
with open('jsn.txt','r') as json_data:
json_dict = json.load(json_data)
由于您的字段名称(将用作字段名称的键)位于不同的字典中,因此我们必须遍历该字典并将其放入列表field_names
中.
since your field names( keys that will act as fieldname) are inside different dicts, we have to go over this dicts and put them in list field_names
.
field_names = [ 'field']
for d in json_dict['field 1']:
field_names.extend(d.keys())
with open('mycsvfile.csv', 'w') as f:
w = csv.DictWriter(f, fieldnames = fieild_names)
w.writeheader()
for k1, arr_v in json_dict.items():
temp = {k2:v for d in arr_v for k2,v in d.items()}
temp['field'] = k1
w.writerow(temp)
输出
field,id,about,can_post,category
field 1,123456,YESH,True,Community
field 2,123456,YESH,True,Community
如果您发现上面的dict理解令人困惑
If you find above dict comprehension confusing
k1 : arr_v
'field 1' = [{ "id": "123456" },...{"category": "Community"}]
for d in arr_v:
k2 : v
d --> { "id": "123456" }
这篇关于将具有嵌套数组的JSON转换为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!