[{"cat1":136803,"cat2":"1.4545","cat3":"0.0885","cat4":"112969"},
{"cat1":1564654,"cat2":"2.5448","cat3":"0.0568","cat4":"5468489"},
{"cat1":5484654,"cat2":"1.8948","cat3":"0.0478","cat4":"898489"}]
I have a JSON structure that looks like the one above.
My code:
import json
from pprint import pprint
with open('file/path') as data_file:
data = json.load(data_file)
data["cat1"]
give me an error that list indicies must be integers not, str
How can I parse this to return only what I want, say "cat1"?
My goal is to parse out what I want from my JSON file and then write that to a CSV file.
Your JSON structure is a list of a dictionary. So, you have to write:
data[0]["cat1"]
To get the values associated with the key cat1
, try:
cat1 = [dct['cat1'] for dct in data]
Notice that data
is a list of dicts, not a dict
itself. So you have to iterate through the items in the list (ie dicts) before you can access the values associated with the key cat1
.
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.