python新手,尝试将json文件转换为csv并编写下面的代码,但不断收到“TypeError:string indices必须是整数”错误。请建议。
import json
import csv
#x= '''open("Test_JIRA.json","r")'''
#x = json.load(x)
with open('Test_JIRA.json') as jsonfile:
x = json.load(jsonfile)
f = csv.writer(open("test.csv", "w"))
# Write CSV Header, If you dont need that, remove this line
f.writerow(["id", "self", "key", "customfield_12608", "customfield_12607"])
for x in x:
f.writerow([x["id"],
x["self"],
x["key"],
x["fields"]["customfield_12608"],
x["fields"]["customfield_12607"]
])
以下是示例1行输入json文件数据:
{"expand":"schema,names","startAt":0,"maxResults":50,"total":100,"issues":[{"expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields","id":"883568","self":"https://jira.xyz.com/rest/api/2/issue/223568","key":"AI-243","fields":{"customfield_22608":null,"customfield_12637":"2017-10-12T21:46:00.000-0700"}}]}
答案 0 :(得分:1)
据我所知,问题在这里
for x in x:
请注意,代码中的x
是dict
,而不是list
。我认为(根据提供的json示例)你需要像
for x in x['issues']:
另外,@ Reti43在评论中注明,dicts
中x['issues']
的键在不同元素之间有所不同。为了使您的代码更安全,您可以使用get
for x in x['issues']:
f.writerow([x.get("id"),
x.get("self"),
x.get("key"),
x.get("fields", {}).get("customfield_12608"),
x.get("fields", {}).get("customfield_12607")
])