我有一个文件,其中包含超过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
当我尝试将最后一个数组(例如“所有者”)替换为整数值时,出现以下错误:IndexError: list index out of range
。
当我严格地将 f.writerow 函数更改为
时f.writerow([key,
type,
x["Result"][key]["Type1"]])
我在一列中接收结果,但是它将所有内容合并为一列,这很有意义。输出图片:https://imgur.com/a/JpDkaAT
我希望将结果根据标签分为单独的列,而不是合并为一列。有人可以协助吗?
谢谢!
答案 0 :(得分:2)
Type1
是一个列表,而不是字典。因此,您需要对其进行迭代,而不是通过键进行引用。
for key in x["Result"]:
# key is now "Example 1" etc.
type1 = x["Result"][key]["Type1"]
# type1 is a list, not a dict
for i in type1:
f.writerow([key,
"Type1",
type1["Owner"],
type1["Description"],
type1["Email"],
type1["Phone"]])
内部for循环可确保您免受“ Type1”列表中仅包含一项的假定。
答案 1 :(得分:1)
这绝对不是最好的例子,但我想优化它。
%f
答案 2 :(得分:0)
想通了!
我将 f.writerow 函数更改为以下内容:
for key in x["Result"]:
type = "Type1"
f.writerow([key,
type,
x["Result"][key]["Type1"][0]["Owner"],
x["Result"][key]["Type1"][0]["Email"]])
...
这使我可以引用对象内的键。希望这可以帮助某人!