简体   繁体   English

遍历嵌套的JSON对象

[英]Iterate through nested JSON object

How do I parse through JSON with unknown variables? 如何通过JSON解析未知变量? I know "Europe" will always exist, but the city names (eg Germany, ...etc) will always be variable. 我知道“欧洲”将一直存在,但是城市名称(例如德国,...等)将始终是可变的。 I am trying to extract the city and hostname from each entry. 我正在尝试从每个条目中提取城市和主机名。

{
  "Europe": {
    "Germany": [
      {
        "hostname": "host1"
      }
    ],
    "Poland": [
      {
        "hostname": "host2"
      }
    ],
    "Denmark": [
      {
        "hostname": "host3"
      }
    ],

Loop through countries['Europe'].items() : 遍历countries['Europe'].items()

countries = {"Europe":
             {"Germany": [{"hostname": "host1"}],
              "Poland": [{"hostname": "host2"}],
              "Denmark": [{"hostname": "host3"}]}
             }    


for k, v in countries["Europe"].items():
    print(k, v[0]['hostname'])

Germany host1
Poland host2
Denmark host3
>>> 

Try with json to load as dictionary: 尝试使用json加载为字典:

import json
contries = """
{
  "Europe": {
    "Germany": [
      {
        "hostname": "host1"
      }
    ],
    "Poland": [
      {
        "hostname": "host2"
      }
    ],
    "Denmark": [
      {
        "hostname": "host3"
      }
    ]
  }
}
"""
country_host = json.loads(contries)
for k,v in country_host['Europe'].items():
    print(k,v[0]['hostname'])

this will print out countries and its host: 这将打印出国家及其主办方:

Denmark host3
Germany host1
Poland host2

You can try using a library like jsonpath-rw and do the following (please check the docs ): 您可以尝试使用jsonpath-rw类的库并执行以下操作(请检查docs ):

from jsonpath_rw import jsonpath, parse
countries = {"Europe":
         {"Germany": [{"hostname": "host1"}],
          "Poland": [{"hostname": "host2"}],
          "Denmark": [{"hostname": "host3"}]}
         }
# To extract the country and hostname  
for country in parse('$.Europe.*').find(countries):
    for city in parse('$..hostname').find(country.value):
        print ('{}: {}'.format(country.path, city.value))
# Germany: host1
# Poland: host2
# Denmark: host3

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

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