[英]iterate through nested JSON
i'm trying to iterate in a json api respons and i'm unable to reach the data i need 我正在尝试在json api响应中进行迭代,但无法访问所需的数据
here is a api response example. 这是一个api响应示例。 "i know it 's not complete or valid json :)"
“我知道它不完整或有效的json :)”
{
"status": "running",
"reasons": [],
"nodes": {
"Server1": {
"status": "running",
and i'm using a simple for loop to iterate throught it ! 我正在使用一个简单的for循环遍历它!
for platforms in sbNode:
request = urllib2.Request(API URL)
json_res = json.load(urllib2.urlopen(request))
for node in json_res['nodes']:
print node['status']
and i'm getting an error message 我收到一条错误消息
TypeError: string indices must be integers TypeError:字符串索引必须是整数
and normaly i just print the for loop to see the json data but it just print Server1. 通常,我只是打印for循环以查看json数据,但它仅打印Server1。
I'm lost here .... 我在这里迷路了....
Help !!! 救命 !!!
Thanks 谢谢
json_res['nodes']
is a dictionary. json_res['nodes']
是一本字典。 Iterating over a dictionary just gives you the keys, so the first value of node
could be, for example, 'Server1'
. 遍历字典只会给您键,因此
node
的第一个值可以是例如'Server1'
。 If you want both the keys and values you can iterate using .items()
: 如果需要键和值,则可以使用
.items()
进行迭代:
for key, node in json_res['nodes'].items():
If you only want the values of the nodes, you can use .values()
: 如果只需要节点的值,则可以使用
.values()
:
for node in json_res['nodes'].values():
You are missing a level of deepness of your data since json_res['nodes']
is a dictionary 您缺少数据的深度知识,因为
json_res['nodes']
是字典
json_res['nodes'] = {
"Server1": {
"status": "running",
...
You can add a nested loop to print servers status: 您可以添加嵌套循环以打印服务器状态:
for node in json_res['nodes']:
for server in node:
print server['status']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.