【问题标题】:Iterate through nested JSON object遍历嵌套的 JSON 对象
【发布时间】:2018-05-13 21:57:47
【问题描述】:

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

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

【问题讨论】:

  • 在我看来 json 格式很差。理想情况下,每个值都应该有一个用于遍历目的的有效键。
  • 您可以尝试将其转换为 python 字典并对其进行迭代。这就是你想要的吗?
  • @Umesh 你能举个例子说明你的意思吗?
  • @EthanB,看到这个"continent": "Europe": { "country": "Germany": [ { "hostname": "host1" } ],

标签: python json python-3.x


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 注意:OP 在 Py3 中询问,因此输出会与您提供的完全不同(不是元组,不是用引号括起来或以 u 为前缀)。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 2014-01-29
      相关资源
      最近更新 更多