![](/img/trans.png)
[英]Whenever I try parsing JSON file I get KeyError in Python
[英]Why do I get a KeyError when I try to access the first item of this JSON file in a python script
我正在尝试遍历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()
"my_services"
的值是字典列表。
processService
内部的service
是字典,而不是列表。 于是
for item in service[0].values():
应该更改为
for item in service.values():
更新:
我可以通过使用字典方法get来弄清楚这一点,该方法在字典中给定键,然后返回关联的值。
我用来获取关联值的代码行是:
def processService(service):
print(service.get("service_name"))
这将返回我的配置列表中的每个关联的service_name。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.