迭代嵌套的JSON对象

时间:2017-11-30 03:46:26

标签: python json python-3.x

如何使用未知变量解析JSON?我知道"欧洲"将永远存在,但城市名称(例如德国,......等)将始终是可变的。我想从每个条目中提取城市和主机名。

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

3 个答案:

答案 0 :(得分:2)

循环通过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
>>> 

答案 1 :(得分:0)

尝试使用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'])

这将打印出国家及其主持人:

Denmark host3
Germany host1
Poland host2

答案 2 :(得分:0)

您可以尝试使用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