Python如何从JSON响应中提取首个type为CLIENTREF的id并解决KeyError报错
问题排查与解决方案
报错原因
- 缩进错误:
if thisdict["type"] == "CLIENTREF"判断逻辑写在了遍历jsonpath_expression.find(r)的循环外部,只有循环结束后最后一个match的值会被赋值给thisdict,一旦最后一个匹配的identifier节点不存在type字段,直接取值就会触发KeyError - 冗余判断:你注释的JsonPath表达式
$..identifier[?(@.type == 'CLIENTREF')].id本身就可以直接过滤出所有type为CLIENTREF的id值,不需要额外遍历后手动判断type - 逻辑漏洞:当前代码不管是否存在空id的情况,都会打印绿色的校验成功提示,不符合校验需求
- 命名不规范:参数名用了Python内置类型关键字
list,存在命名冲突风险
修复后的实现代码
import requests from jsonpath_ng import parse from termcolor import colored def checkParent(item_list): # 提前编译JsonPath表达式,提升循环效率 jsonpath_expression = parse("$..identifier[?(@.type == 'CLIENTREF')].id") for item in item_list: cdwParenturl = f"http://cdwu/cdw/counterparties/{item}/?yyyy-mm-dd={dateinplay}" r = requests.get(cdwParenturl).json() # 直接提取所有符合条件的id值 clientref_ids = [match.value for match in jsonpath_expression.find(r)] # 判断是否存在符合条件的id,且第一个id不为空 if not clientref_ids or clientref_ids[0].strip() == "": print(colored(f"The parent {item} does not have ultimateParent", "red")) continue # 第一个符合要求的id可直接调用,此处保留调试入口 first_clientref_id = clientref_ids[0] print(colored(f"All counterparties have parent", "green")) checkParent(r_mheu_trade)
实现逻辑说明
- 提前编译JsonPath表达式,避免循环内重复编译浪费性能
- 用JsonPath直接过滤出所有type为CLIENTREF的id值,不需要二次遍历判断
- 优先判断是否存在符合条件的id、以及第一个id是否为空,为空直接打印错误提示跳过当前条目
- 所有条目校验通过后才打印全局成功提示
内容的提问来源于stack exchange,提问作者Bruno Lorena
相关产品推荐
相关产品推荐

