Reputation: 2065
I'm trying to convert JSON to CSV. I got a "TypeError: string indices must be integers"
I looked at Q&As such as these: Why am I seeing "TypeError: string indices must be integers"?, but I think I am understanding something wrongly.
Snippets of the JSON and code follows:
import csv
import json
x = """{"status": "user data saved", "lastupdate": "2015-04-24", "offeredBonus": true, "bround_rn": 19, "currenttrial": 30, "assignmentId": "abc", "workerId": "def", "condition": 1}"""
x = json.loads(x)
print x
f = csv.writer(open("tested.csv","wb+"))
# write CSV header
f.writerow(["worker_id","offeredBonus","trial","rewards"])
for a in x:
print a, type(a) # for debugging
print x, type(x) # for debugging
f.writerow(a["status"])
...
It is the last line ("writerow") that gives me an error. Furthermore I notice that type(x) is a dictionary, but type(a) is unicode.
Does that mean I must use the ast package (Convert unicode string dictionary into dictionary in python) to convert unicode into a dictionary, so I won't encounter the error? Or is there a simpler way out?
Upvotes: 0
Views: 83
Reputation: 599490
x
is a dictionary, because that's what you get from the json.loads()
call. When you do for a in x
, you are given the keys. That's why you get that error: a
is a string, ie the first key in x
.
I think you are using the wrong data. It doesn't make sense to try and make a CSV of a single dictionary, because there's only one row. Perhaps you meant x
to be a list of dictionaries?
x = """
[
{"status": "user data saved", ...},
{"status": "another_status", ...},
]
"""
Upvotes: 2