Python解析嵌套JSON提取所有sw_items名称及解决KeyError问题
嵌套JSON提取sw_items字段解决方案
报错根因
- 层级访问错误:sw_items的完整路径为
Module -> components -> 对应Component对象 -> sw_items,直接从Module层级访问不存在的字段自然触发KeyError - 未做边界处理:部分Module没有components字段,未做非空判断直接访问会触发异常
正确实现代码(Python示例)
# 初始化结果列表 list_sw_items = [] # 遍历所有Module对象,your_json_data替换为你的实际JSON数据变量 for module in your_json_data.get("modules", []): # 无components字段的Module直接跳过,默认返回空列表不会触发遍历异常 components = module.get("components", []) for component in components: # 无sw_items字段的Component直接跳过 sw_items = component.get("sw_items", []) for item in sw_items: # 提取sw_item的名称,字段名可根据你的实际结构调整 item_name = item.get("name") if item_name: list_sw_items.append(item_name)
代码说明
- 所有字段都用
dict.get()方法访问,第二个参数设置默认空值,完全避免KeyError - 每层都做非空校验,兼容无对应字段的异常场景
- 可根据实际JSON结构调整顶层Module的存储键、sw_items的名称字段等参数
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

