2017-10-16 114 views
0

python新手,試圖將json文件轉換爲csv,並在代碼中寫下,但不斷收到「TypeError:字符串索引必須是整數」錯誤。請建議。錯誤: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"}}]} 
+0

你可以請加輸入JSON文件和輸出錯誤,因爲它是在控制檯 – RejeeshChandran

+0

所示,請提供完整的回溯。 – Reti43

回答

1

至於我看到的問題是在這裏

for x in x: 

注意,那x在你的代碼是一個dict,不是list。我認爲(基於JSON提供的例子),你需要像

for x in x['issues']: 

此外,@ Reti43注意在評論,說dictsx['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") 
       ]) 
+2

變量名稱沒有什麼區別,因爲循環目標只被求值一次。 'for x in x'失敗是因爲它正在迭代dict的*鍵*(這解釋了「字符串索引必須是整數」錯誤)。你的答案的第二部分是真正重要的東西(儘管'x中的x''問題''也會起作用)。 – ekhumoro

+0

@ekhumoro感謝評論,我會更正我的回答 – kvorobiev

+2

問題就像ekhumoro描述的一樣。但是,當代碼嘗試訪問自定義字段鍵時,它仍然處於一個令人討厭的驚喜,因爲它們在不同問題之間似乎有所不同。另外,僅僅因爲'for x in x ['issues']'會起作用,這並不意味着在循環結束時最後一項不會使對象蒙上陰影。因此,在x ['issues']中執行問題仍然是可取的。 – Reti43

相關問題