Digitaldw Gannett
Digitaldw Gannett

Reputation: 69

How to loop through JSON in Python

I can't figure out how to loop though a JSON object that is deeper than 1 level. The object is:

{
  "data":[
    {
      "id":"251228454889939/insights/page_fan_adds_unique/day",
      "name":"page_fan_adds_unique",
      "period":"day",
      "values":[
        {
          "value":9,
          "end_time":"2012-05-29T07:00:00+0000"
        },
        {
          "value":5,
          "end_time":"2012-05-30T07:00:00+0000"
        }
      ],
      "title":"Daily New Likes",
      "description":"Daily The number of new people who have liked your Page (Unique Users)"
    },
    {
      "id":"251228454889939/insights/page_fan_adds/day",
      "name":"page_fan_adds",
      "period":"day",
      "values":[
        {
          "value":9,
          "end_time":"2012-05-29T07:00:00+0000"
        },
        {
          "value":5,
          "end_time":"2012-05-30T07:00:00+0000"
        }
      ],
      "title":"Daily New Likes",
      "description":"Daily The number of new people who have liked your Page (Total Count)"
    }
  ]
}

Code:

def parseJsonData(data):
    output_json = json.loads(data)
    for i in output_json:
        print i
        for k in output_json[i]:
            print k

How come I can't access the object like: output_json[data][id]? I get an error if I try this:

string indice must be an integer

Upvotes: 2

Views: 36159

Answers (2)

jdi
jdi

Reputation: 92559

Being that your "data" key is actually a list of objects, you cannot access the items by their "id" field directly. You would need to access each item by a list index such as:
output_json["data"][0]["id"]

Now, if what you want to do is to be able to index the members of "data" by the "id" field as the key, you could reformat your data:

# make "data" a dict {id: item, }, instead of list [item1, item2, ...]
output_json['data'] = dict((item['id'], item) for item in json_data['data'])

print output_json['data']
# {'251228454889939/insights/page_fan_adds_unique/day': ...

print output_json['data']['251228454889939/insights/page_fan_adds_unique/day']
# {'description': 'Daily The number of new p ...

# ways to loop over "data"
for id_, item in output_json['data'].iteritems():
    print id_, item

for item in output_json['data'].itervalues():
    print item

Otherwise what you have to do is just loop over "data", since there is no real correlation between the index and the object:

for item in output_json["data"]:
    print item['id']

# 251228454889939/insights/page_fan_adds_unique/day
# 251228454889939/insights/page_fan_adds/day

Upvotes: 5

BrenBarn
BrenBarn

Reputation: 251345

What you pasted is not valid JSON. There is an unmatched [ after "data".

Based on this, I would guess that maybe the data isn't what you think it is. If the value of output_json[data] is a list, then you won't be able to access output_json[data][id]. Instead you'll have to do something like output_json[data][0][id], where the [0] accesses the first item in the list.

Upvotes: 2

Related Questions