我不知道如何遍历一个深度超过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 must be an integer
粘贴的内容不是有效的JSON。有一个不匹配的[在“数据”之后]。
基于这个,我想也许数据不是你想象的那样。如果输出json[data]的值是一个列表,那么您将无法访问
output_json[data][id]
。相反,您将不得不执行类似于output_json[data][0][id]
的操作,其中[0]访问列表中的第一个项。由于您的“数据”键实际上是一个对象列表,因此不能直接通过它们的“id”字段访问这些项。您需要通过列表索引访问每个项,例如:
output_json["data"][0]["id"]
现在,如果您希望能够通过“id”字段作为键来索引“data”的成员,则可以重新格式化数据:
否则,您只需循环“数据”,因为索引和对象之间没有真正的关联:
相关问题 更多 >
编程相关推荐