以下是我拥有的示例json文档或json变量。我正在使用python提取输出部分中提到的必填字段。
有人可以帮忙吗?
json_variable =
{
"server01":{
"address":"server01:5454",
"options":{ },
"state":"online"
},
"server02":{
"address":"server02:5454",
"options":{ },
"state":"online"
},
"server03":{
"address":"server03:5454",
"options":{ },
"state":"online"
}
}
for x in json_variable:
print(x["address"])
Error:
Traceback (most recent call last):
File "<string>", line 30, in <module>
File "<string>", line 18, in getServerStatus
TypeError: 'shell.Dict' object is not iterable
我可以通过如下所示对字段进行硬编码来获得所需的输出,但是我想动态地做到这一点,因为服务器的数量取决于查询的系统和返回的json。
print(json_variable["server01"]["address"])
print(json_variable["server02"]["address"])
print(json_variable["server03"]["address"])
必需的输出:
server01:5454 --> online
server02:5454 --> online
server03:5454 --> online
答案 0 :(得分:1)
将其作为字典进行处理:
for k, v in sample.items():
print(v['address'] + "-->" + v['state'])
答案 1 :(得分:1)
这是从JSON获取服务器状态的另一种方法。
json_info = {
"server01":{
"address":"server01:5454",
"options":{ },
"state":"online"
},
"server02":{
"address":"server02:5454",
"options":{ },
"state":"online"
},
"server03":{
"address":"server03:5454",
"options":{ },
"state":"online"
}
}
for server in json_info.values():
server_status = server['state']
if 'online' in server_status:
server_name = server.get('address')
print ('{} is online'.format(server_name.split(':')[0]))
# output
# server01 is online
# server02 is online
# server03 is online
#
# print ('{} --> online'.format(server_name))
# output
# server01:5454 --> online
# server02:5454 --> online
# server03:5454 --> online
else:
server_name = server.get('address')
print('{} is offline'.format(server_name.split(':')[0]))