简体   繁体   English

如何从json输出中递归提取特定字段?

[英]How to extract specific fields recursively from json output?

Below is the sample json document or json variable I have.下面是我拥有的示例 json 文档或 json 变量。 I'm using python for extracting the required fields as mentioned int the output section.我正在使用 python 来提取输出部分中提到的所需字段。

Can someone help on how to do this?有人可以帮助了解如何做到这一点吗?

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

I can get the required output by hard coding the fields as below, but i would like to do it dynamically as the number of servers vary depending upon the system queried and json returned.我可以通过对以下字段进行硬编码来获得所需的输出,但我想动态地执行此操作,因为服务器的数量取决于查询的系统和返回的 json。

print(json_variable["server01"]["address"])
print(json_variable["server02"]["address"])
print(json_variable["server03"]["address"])

Required Output :所需输出

server01:5454 --> online 
server02:5454 --> online
server03:5454 --> online

Treat it as a dictionary:将其视为字典:

for k, v in sample.items():
      print(v['address'] + "-->" + v['state'])

Here's another way to get the server status from the JSON.这是从 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]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM