Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
[{"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.

share|improve this question
4  
Have you tried data[0]["cat1"]? –  Tomalak May 9 '13 at 11:56

2 Answers 2

Your JSON structure is a list of a dictionary. So, you have to write:

data[0]["cat1"]
share|improve this answer

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 (i.e. dicts) before you can access the values associated with the key cat1.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.