data = "[{"id":"abc, "content":"Bye", "child": [{"id":"dsd", "parent id": "abc", "content": "dds"}]}, {"id": xcv, "content": "hello"}]"
with open("data.json","w") as f:
json.dump(data, f)
# reads it back
with open("data.json","r") as f:
parsed_json = json.load(f)
for e in parsed_json:
print (e["content"])
I would like to extract Bye and hello but i stumble upon this error. Was wondering how to loop through
TypeError Traceback (most recent call last)
<ipython-input-2-1aa8088c77a7> in <module>
46
47 for e in parsed_json:
---> 48 print (e["content"])
49
50
TypeError: string indices must be integer
Don't use json.dump
to write a string to a file. Use it to write a data structure (list, dictionary, etc.) to a file.
So, don't put the original value for your data
variable inside quotes.
Also, you're missing some of the quotes in the data ( abc
is missing the closing quote, and xcv
is missing both quotes).
import json
data = [{"id":"abc", "content":"Bye", "child": [{"id":"dsd", "parent id":"abc", "content":"dds"}]},
{"id":"xcv", "content":"hello"}]
with open("data.json","w") as f:
json.dump(data, f)
# reads it back
with open("data.json","r") as f:
parsed_json = json.load(f)
for e in parsed_json:
print (e["content"])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.