如何使用Python从嵌套JSON响应中提取特定字段值
报错原因
你遇到的是KeyError: 'Tags'异常,触发原因是部分Instance列表中的字典对象不存在Tags键,直接用identifier["Tags"]的方式取值时,只要目标键不存在就会直接抛出异常,即使你给出的示例结构中所有实例都带Tags字段,实际接口返回的部分实例条目可能缺失该字段。
修复后的代码
# 可选:初始化列表存储符合条件的实例ID matched_ids = [] if response["Instance"]: print("1-->",response["Instance"]) for identifier in response["Instance"]: print("2-->", identifier) if identifier.get("id"): current_id = identifier["id"] print("3-->", current_id) # 用get方法安全取Tags,不存在时默认返回空列表 tags = identifier.get("Tags", []) if tags: print("4-->", tags) for tag in tags: print("5-->", tag) if tag.get('Key') == 'test' and tag.get('Value') == 'test': print("6--> test present ") matched_ids.append(current_id) # 打印所有符合条件的ID print("符合条件的实例ID:", matched_ids)
关键修改说明
- 所有字典取值都优先用
get()方法,避免键不存在时抛出异常,第二个参数可以自定义键不存在时的默认返回值 - 修正了原代码中遍历tag时的打印笔误,原代码重复打印整个Tags列表,改为打印当前遍历的单个tag对象
- 新增了符合条件ID的收集逻辑,如果你不需要可以直接删除对应代码即可
内容的提问来源于stack exchange,提问作者Mia
相关产品推荐
相关产品推荐

