Python pandas解析API嵌套JSON数据报KeyError、TypeError问题求助
嵌套JSON提取报错排查方案
错误根本原因
KeyError: 'XrfSurveys':目标字段XrfSurveys不是JSON根级字段,存在更深的嵌套层级,或部分API响应中不存在该字段TypeError: list indices must be integers or slices, not str:取值过程中某一级节点返回的是列表类型,你直接使用字符串key对列表做索引操作
落地解决步骤
- 先打印完整响应结构确认层级,先跑以下代码:
import json import requests # 替换为你自己的API请求逻辑 response = requests.get("你的API接口地址", headers=你的请求头) response_json = response.json() # 打印根节点类型和完整结构,确认目标字段路径 print("根节点类型:", type(response_json)) print("完整响应结构:\n", json.dumps(response_json, indent=2, ensure_ascii=False))
- 按打印出来的层级写取值逻辑,加容错避免报错:
举个通用参考示例,如果你打印后发现目标字段存在于data字段下的每个列表元素里,可直接套用:
import pandas as pd target_fields = ["XrfSurveys", "XrfQaqcSurveys", "XrfCorrectedSurveys", "XrfQaqcCorrectedSurveys"] result = [] # 根节点是列表就直接遍历,是字典就先取上一级节点 if isinstance(response_json, list): parent_nodes = response_json else: # 替换为你实际的上一级字段名,比如data/result等 parent_nodes = response_json.get("data", []) for node in parent_nodes: for field in target_fields: # 不存在的字段默认返回空列表,避免KeyError field_value = node.get(field, []) if isinstance(field_value, list): result.extend(field_value) elif field_value: result.append(field_value)
- 转DataFrame导出CSV:
df = pd.DataFrame(result) # 用utf-8-sig编码避免Excel打开乱码 df.to_csv("xrf_export.csv", index=False, encoding="utf-8-sig")
内容的提问来源于stack exchange,提问作者Lowell Lowellcraft
相关产品推荐
相关产品推荐

