使用Python读取JSON文件属性并按Vendor属性过滤模块时出现KeyError问题求助
解决JSON解析与KeyError问题的方案
看起来你的问题主要出在原始JSON的语法错误和代码中缺乏异常/类型检查这两个方面,咱们一步步来解决:
1. 先修正原始JSON的语法问题
你的原始JSON有几个致命错误,直接导致解析后的数据结构完全不符合预期:
Attributes": { "some" }:JSON对象必须是键值对格式,这里改成"Attributes": { "key": "some" }(如果是数组就用["some"])- 重复的
"Module1"键:JSON规范中重复键的行为是未定义的,大多数解析器会保留最后一个值(也就是4),这直接把原本的Module1覆盖成了整数,后面的Description等键也变成了顶级键,不属于任何模块 - 最后一段的模块名错误:你预期结果里有Module4,所以那段应该是
"Module4": { ... },而不是把一堆键放在顶级层级
修正后的合法JSON应该是这样:
{ "Module1": { "Description": "", "Layer": "1", "SourceDir": "path", "Attributes": { "key": "some" }, "Vendor": "comp" }, "Module2": { "Description": "", "Layer": "2", "SourceDir": "path", "Attributes": { "key": "some" }, "Vendor": "" }, "Module3": { "Description": "", "Layer": "3", "SourceDir": "path", "Attributes": { "key": "some" }, "Vendor": "" }, "Module4": { "Description": "", "Layer": "4", "SourceDir": "path", "Attributes": { "key": "some" }, "Vendor": "comp" } }
2. 修正Python代码,避免KeyError
之前的代码没有处理以下情况:
- JSON解析失败的情况
- 模块数据不是字典的情况(比如被覆盖的Module1变成了整数4)
- 模块缺少
Vendor或SourceDir键的情况
这里给你一个更健壮的版本:
import json # 读取修正后的JSON(如果是文件的话,用open()读取) json_content = ''' { "Module1": { "Description": "", "Layer": "1", "SourceDir": "path", "Attributes": { "key": "some" }, "Vendor": "comp" }, "Module2": { "Description": "", "Layer": "2", "SourceDir": "path", "Attributes": { "key": "some" }, "Vendor": "" }, "Module3": { "Description": "", "Layer": "3", "SourceDir": "path", "Attributes": { "key": "some" }, "Vendor": "" }, "Module4": { "Description": "", "Layer": "4", "SourceDir": "path", "Attributes": { "key": "some" }, "Vendor": "comp" } } ''' list_components = [] sourceDirList = [] try: # 解析JSON为字典 swc_list = json.loads(json_content) except json.JSONDecodeError as err: print(f"JSON解析失败:{err}") else: # 遍历所有模块 for module_name, module_info in swc_list.items(): # 先确保模块信息是字典,并且Vendor匹配"comp" if isinstance(module_info, dict) and module_info.get("Vendor") == "comp": list_components.append(module_name) # 用get()避免SourceDir不存在时的KeyError,这里可以设置默认值比如"" sourceDirList.append(module_info.get("SourceDir", "")) # 输出结果 print("匹配的模块:", list_components) print("对应的SourceDir:", sourceDirList)
为什么之前会出现KeyError?
- 原始JSON解析后,重复的
Module1被覆盖成了整数4,当你尝试访问swc_list['Module1']['Vendor']时,会因为4不是字典而抛出错误(实际是TypeError,但如果遍历到顶级的Description键,它的值是空字符串,访问['Vendor']就会抛出KeyError) - 代码没有检查模块数据的类型,也没有用
get()方法安全获取键值,导致遇到异常结构时直接报错
运行修正后的代码,就能得到你预期的结果:Module1和Module4,以及对应的SourceDir。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

