Python读取JSON报KeyError: 'name' 如何提取指定字段数据
错误原因
触发KeyError: 'name'是因为你的字段访问路径和JSON实际结构不匹配:
- 加载得到的顶层字典只有一个键
businessModelInfo,不存在顶层的name字段 - 你需要的所有业务条目都存储在
businessModelInfo对应的字典值中,以条目ID作为键 description字段没有放在条目顶层,而是嵌套在nodeInfo子字典内
另外你贴的JSON样例使用单引号包裹键值,不符合标准JSON的双引号规范,如果本地文件确实是单引号格式,json.loads会先抛出解析错误,需要换用其他方式解析。
正确读取代码
如果你的文件是标准双引号格式的合法JSON,用以下代码即可提取所有需要的字段:
import json # 显式指定utf-8编码,避免Windows默认编码导致的乱码问题 with open(r'C:\Users\UserName\Projects\project_one\test.json', 'r', encoding='utf-8') as f: data = json.load(f) # 直接传入文件对象即可,不需要先调用f.read() extracted_items = [] # 遍历businessModelInfo下所有条目 for item in data['businessModelInfo'].values(): item_data = { "parentId": item["parentId"], "id": item["id"], "name": item["name"], "description": item["nodeInfo"]["description"] } extracted_items.append(item_data) print(item_data)
如果你的文件实际是单引号包裹的Python字典格式(非标准JSON),把文件解析部分替换为以下代码即可:
import ast with open(r'C:\Users\UserName\Projects\project_one\test.json', 'r', encoding='utf-8') as f: data = ast.literal_eval(f.read())
运行结果
对应你提供的样例数据,代码会输出3条提取完成的结构化数据:
{'parentId': '52ff2cfce4b0b193ed664d1a', 'id': '52ff2dd1e4b0b193ed664d41', 'name': 'Network Security', 'description': 'Platform for the security monitoring, detection & prevention of unauthorized access, misuse & modification to the enterprise network'} {'parentId': '52ff2cfce4b0b193ed664d1a', 'id': '52ff2df2e4b0b193ed664d43', 'name': 'Application Security', 'description': 'Application security testing, vulnerability assessment & runtime application protection'} {'parentId': '52ff2cfce4b0b193ed664d1a', 'id': '52ff2e04e4b0b193ed664d45', 'name': 'IAM', 'description': 'Identity & Access Management (IAM) solution for the user login, authentication and authorization'}
内容的提问来源于stack exchange,提问作者BQuist
相关产品推荐
相关产品推荐

