【问题标题】:Why do I get a KeyError when I try to access the first item of this JSON file in a python script当我尝试在 python 脚本中访问此 JSON 文件的第一项时,为什么会出现 KeyError
【发布时间】:2019-11-19 03:52:46
【问题描述】:

我正在尝试遍历 JSON 配置文件,并一次处理每个服务。我想在这段代码中获取 service_name,但它给了我一个 KeyError: 0。

我尝试过以各种方式循环它,但我尝试的每种方法都给了我关键错误。

{
  "my_services": [
    {
      "service_name" : "Exchange Online",
      "region": [
        "NorthCentral",
        "SouthCentral"
      ],
      "firewall": [
        "ABC",
        "DEF"
      ],
      "firewall_ip" : "12.23.34.455",
      "firewall_type" : "cde",
      "endpointURL" : "something.com",
      "parserType" : "parseO365Delta.py"
    },
    {
      "service_name" : "Microsoft 365 Common and Office Online",
      "region": [
        "NorthCentral",
        "SouthCentral"
      ],
      "firewall": [
        "ABC"
      ],
      "firewall_ip" : "98.87.76.655",
      "firewall_type" : "abc",
      "endpointURL" : "alsosomething.com",
      "parserType" : "parseO365Delta.py"
    }
  ]
}
import json
import subprocess

def processService(service):
    for item in service[0].values():
        print(item)

def main():
    with open('config.json', 'r') as config:
        config_list = json.load(config)

    for services in config_list["my_services"]:
        processService(services) 

if __name__ == "__main__":
    main()

【问题讨论】:

    标签: python json dictionary for-loop iteration


    【解决方案1】:

    更新:

    我能够通过使用字典方法get来解决这个问题,它给定字典中的一个键,返回相关的值。

    我用来获取关联值的代码行是:

    def processService(service):
        print(service.get("service_name"))
    

    这将返回我的配置列表中的每个关联的 service_name。

    【讨论】:

      【解决方案2】:

      "my_services" 的值是一个字典列表。

      processService 内部的service 是字典,而不是列表。因此

      for item in service[0].values():
      

      应该改为

      for item in service.values():
      

      【讨论】:

      • 对,但这会返回列表中的每个项目,而我只想要第一个是“service_names”。我能够找到一个解决方案,我在下面发布。谢谢你也花时间帮助我。
      猜你喜欢
      • 2012-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      • 2013-01-03
      • 2020-10-18
      • 2015-01-24
      相关资源
      最近更新 更多