简体   繁体   中英

Iterate through nested JSON object

How do I parse through JSON with unknown variables? 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":
             {"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:

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 ):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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