如何使用Python过滤API返回的JSON结果提取指定数据
Python实现JSON指定字段筛选的方法
首先需要说明:你给出的预期返回格式不符合JSON语法规范,JSON标准不允许同一个对象内存在同名键,你写的两个custPermId键在实际解析时只会保留最后一个值9234,直接丢失1234的匹配结果,行业通用做法是用数组存储所有匹配到的ID,下面是可直接运行的实现代码:
实现步骤
- 用Python内置的
json模块做JSON格式和Python字典的转换,不需要安装额外第三方依赖 - 解析API返回的JSON内容为Python可操作的字典对象
- 遍历
custAnalysis列表,筛选出taxId等于"8888"的条目,收集对应的custPermId值,按需要转成数字类型 - 构造合规的结果结构,再转回JSON格式即可
完整代码
import json # 替换为你实际调用API拿到的响应文本,如果用requests库发请求,直接用resp.json()即可拿到解析后的字典 api_raw_resp = """ { "custAnalysis": [ { "custPermId": "1234", "custType": "Business", "taxId": "8888", "custAddr": { "fullName": "Testing LIMITED", "addr1": "6734 APAPA RD" } }, { "custPermId": "5678", "custType": "Business", "taxId": "9999", "custAddr": { "fullName": "SUPERMAN LLC", "addr1": "6734 APAPA RD" } }, { "custPermId": "9234", "custType": "Business", "taxId": "8888", "custAddr": { "fullName": "DONALD LLC", "addr1": "6734 APAPA RD" } } ] } """ # 解析JSON为Python字典 resp_dict = json.loads(api_raw_resp) # 筛选符合条件的客户ID target_tax_id = "8888" matched_perm_ids = [] for cust_item in resp_dict.get("custAnalysis", []): if cust_item.get("taxId") == target_tax_id: # 原始数据里custPermId是字符串,转成int匹配数字格式要求 matched_perm_ids.append(int(cust_item.get("custPermId"))) # 构造返回结果 final_result = { "custQueryResult": { "custPermIdList": matched_perm_ids } } # 转成格式化的JSON字符串输出 print(json.dumps(final_result, indent=2))
运行输出
{ "custQueryResult": { "custPermIdList": [1234, 9234] } }
注意:如果你强行要求生成带重复
custPermId键的非标准JSON,只能通过手动拼接字符串实现,这种格式无法被绝大多数JSON解析工具正确识别,会导致数据丢失,绝对不建议在正式业务中使用。
内容的提问来源于stack exchange,提问作者Baba
相关产品推荐
相关产品推荐

