[英]Error: TypeError: string indices must be integers
python的新手,嘗試將json文件轉換為csv並編寫了以下代碼,但始終收到“ TypeError:字符串索引必須為整數”錯誤。 請提出建議。
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"}}]}
據我所知問題在這里
for x in x:
請注意,代碼中的x
是dict
,不是list
。 我認為(基於提供的json示例),您需要類似
for x in x['issues']:
另外,@ Reti43在注釋中指出, x['issues']
的dicts
鍵在元素之間有所不同。 為了使您的代碼更安全,可以使用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")
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.