Reputation: 137
New to python, trying to convert json file to csv and wrote below code but keep getting "TypeError: string indices must be integers" error. Please suggest.
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"]
])
Here is sample 1 row input json file data:
{"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"}}]}
Upvotes: 0
Views: 1580
Reputation: 5070
As far as I see problem is here
for x in x:
Note, that x
in your code is a dict
, not list
. I think (based on provided json example) you need something like
for x in x['issues']:
Also, @Reti43 note in comment, that keys of dicts
in x['issues']
vary between elements. To make your code more safe you could use 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")
])
Upvotes: 1