Python处理JSON配置文件触发KeyError:0的问题求助
解决KeyError: 0问题:访问JSON配置时的错误分析与修复
你遇到的KeyError: 0其实是个典型的逻辑小失误——你把单个字典对象当成了列表来用索引访问,咱们一步步拆解问题:
问题根源
看你的代码流程:
config_list["my_services"]是一个包含多个服务字典的列表,比如第一个元素就是{"service_name": "Exchange Online", ...}这种完整的字典。- 在
main()的循环里,for services in config_list["my_services"]每次迭代拿到的services,已经是单个服务的字典了,不是列表。 - 但你把这个字典传给
processService后,函数里写了service[0].values()——字典是靠键(比如"service_name")来访问元素的,根本没有索引0,所以直接触发KeyError。
修正后的代码
只需要把processService里的service[0]去掉,直接遍历传入的字典即可:
import json import subprocess def processService(service): # 直接遍历单个服务字典的所有值 for item in service.values(): print(item) def main(): with open('config.json', 'r') as config: config_list = json.load(config) # 每次循环拿到单个服务字典,直接传入函数 for service in config_list["my_services"]: processService(service) if __name__ == "__main__": main()
如果你想专门获取service_name
如果你的核心需求是逐个提取service_name并处理,更直接的写法可以是这样(还能避免键不存在的风险):
def processService(service): # 用get方法更安全,键不存在时返回None,不会抛错 service_name = service.get("service_name") if service_name: print(f"开始处理服务: {service_name}") # 这里可以添加你的业务逻辑,比如调用subprocess执行脚本等 def main(): with open('config.json', 'r') as config: config_list = json.load(config) for service in config_list["my_services"]: processService(service)
或者甚至可以简化到main函数里直接处理,省去函数调用的步骤,看你的代码结构需求。
内容的提问来源于stack exchange,提问作者Popilofu




