[英]Convert JSON to CSV with multiple keys
我编写代码将 JSON 文件转换为 CSV。 此脚本有效,但不适用于 JSON 中的多个键。
我有错误:
Traceback (most recent call last):
File "test1.py", line 27, in <module>
for j in data[i]:
KeyError: 0
你可以帮帮我吗?
import os
import csv
import json,requests
from collections import OrderedDict
from collections import defaultdict
headers = {
****
****
}
response = requests.get('https://www.exemple.com', headers=headers)
data = response.json()
#print (data)
#print("JSON file loaded")
# get all keys in json objects
keys = []
for i in range(0,len(data)):
for j in data[i]:
if j not in keys:
keys.append(j)
# map data in each row to key index
converted = []
converted.append(keys)
for i in range(0,len(data)):
row = []
for j in range(0,len(keys)):
if keys[j] in data[i]:
row.append(data[i][keys[j]])
else:
row.append(None)
converted.append(row)
with open("filename.csv", 'w') as outfile:
writer = csv.writer(outfile)
writer.writerows(converted)
例如,对于这个复杂的 json,它不起作用:
{
"count": 13,
"virtualmachine": [
{
"id": "1082e2ed-ff66-40b1-a41b-26061afd4a0b",
"name": "test-2",
"displayname": "test-2",
"securitygroup": [
{
"id": "9e649fbc-3e64-4395-9629-5e1215b34e58",
"name": "test",
"tags": []
}
],
"nic": [
{
"id": "79568b14-b377-4d4f-b024-87dc22492b8e",
"networkid": "05c0e278-7ab4-4a6d-aa9c-3158620b6471"
},
{
"id": "3d7f2818-1f19-46e7-aa98-956526c5b1ad",
"networkid": "b4648cfd-0795-43fc-9e50-6ee9ddefc5bd"
"traffictype": "Guest"
}
],
"hypervisor": "KVM",
"affinitygroup": [],
"isdynamicallyscalable": false
}
]
}
你这里有一个错误:
keys = []
for i in range(0,len(data)): #data is a `dict`
for j in data[i]: # <-- error: i is an int, not a key in your data
if j not in keys:
keys.append(j)
如果您想获取dict
中的顶级键,则dict
可以将其提供给您:
for key in my_dict:
print(key)
但看起来你正试图从你的data
中获取值。 dict
也可以给你这个:
for value in my_dict.values():
print(value)
或者您可以同时获得两者:
for key, value in my_dict.items():
print(key, value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.