我有一个包含5000多个对象的数组的文件。但是,我很难将JSON文件的一个特定部分转换为CSV格式的适当列。
下面是我的数据文件的示例版本:
{
"Result": {
"Example 1": {
"Type1": [
{
"Owner": "Name1 Example",
"Description": "Description1 Example",
"Email": "example1_email@email.com",
"Phone": "(123) 456-7890"
}
]
},
"Example 2": {
"Type1": [
{
"Owner": "Name2 Example",
"Description": "Description2 Example",
"Email": "example2_email@email.com",
"Phone": "(111) 222-3333"
}
]
}
}
}
这是我当前的代码:
import csv
import json
json_file='example.json'
with open(json_file, 'r') as json_data:
x = json.load(json_data)
f = csv.writer(open("example.csv", "w"))
f.writerow(["Address","Type","Owner","Description","Email","Phone"])
for key in x["Result"]:
type = "Type1"
f.writerow([key,
type,
x["Result"][key]["Type1"]["Owner"],
x["Result"][key]["Type1"]["Description"],
x["Result"][key]["Type1"]["Email"],
x["Result"][key]["Type1"]["Phone"]])
我的问题是我遇到了这个问题:
Traceback (most recent call last):
File "./convert.py", line 18, in <module>
x["Result"][key]["Type1"]["Owner"],
TypeError: list indices must be integers or slices, not str
当我试图将最后一个数组(如“Owner”)替换为整数值时,收到以下错误:
IndexError: list index out of range
.
当我严格地改变
书面文件
功能到
f.writerow([key,
type,
x["Result"][key]["Type1"]])
我在一个列中收到结果,但它将所有内容合并到一个列中,这是有意义的。输出图片:
https://imgur.com/a/JpDkaAT
我希望根据标签将结果分隔成单独的列,而不是合并成一列。有人能帮忙吗?
谢谢您!