我有一个包含超过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函数严格更改为
f.writerow([key,
type,
x["Result"][key]["Type1"]])
我在一个列中接收结果,但它将所有内容合并到一个列中,这是有意义的。输出图片:https://imgur.com/a/JpDkaAT
我希望根据标签将结果分离为单独的列,而不是合并为一列。有人能帮上忙吗?
谢谢!
发布于 2019-05-28 06:18:30
数据结构中的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“在列表中只有一项的假设。
发布于 2019-05-28 06:16:24
这肯定不是最好的例子,但我想优化它。
import csv
def json_to_csv(obj, res):
for k, v in obj.items():
if isinstance(v, dict):
res.append(k)
json_to_csv(v, res)
elif isinstance(v, list):
res.append(k)
for el in v:
json_to_csv(el, res)
else:
res.append(v)
obj = {
"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"
}
]
}
}
}
with open("out.csv", "w+") as f:
writer = csv.writer(f)
writer.writerow(["Address","Type","Owner","Description","Email","Phone"])
for k, v in obj["Result"].items():
row = [k]
json_to_csv(v, row)
writer.writerow(row)
发布于 2019-05-28 06:17:08
想明白了!
我将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"]])
...
这允许我引用对象中的键。希望这能帮助下一个人!
https://stackoverflow.com/questions/56332800
复制相似问题