如何在Python中循环JSON

时间:2012-06-01 18:53:53

标签: python json loops

我无法弄清楚如何循环一个深度超过1级的JSON对象。对象是:

{
  "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)"
    }
  ]
}

代码:

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

为什么我无法访问像output_json[data][id]这样的对象? 如果我尝试这个,我会收到错误:

  

string indice必须是整数

2 个答案:

答案 0 :(得分:5)

由于您的“数据”键实际上是一个对象列表,因此您无法直接通过其“id”字段访问这些项目。您需要通过列表索引访问每个项目,例如:
output_json["data"][0]["id"]

现在,如果你想要做的是能够通过“id”字段索引“数据”的成员作为键,你可以重新格式化你的数据:

# 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

否则你要做的就是循环“数据”,因为索引和对象之间没有真正的相关性:

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

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

答案 1 :(得分:2)

您粘贴的内容不是有效的JSON。有一个无与伦比的[后“数据”。

基于此,我猜可能数据不是你想象的那样。如果output_json [data]的值是列表,那么您将无法访问output_json[data][id]。相反,你必须做output_json[data][0][id]之类的事情,其中​​[0]访问列表中的第一项。