
本文详解如何将 API 返回的 JSON 字典(而非 JSON 文件路径)安全、高效地转换为 Pandas DataFrame,避免 ValueError: Invalid file path or buffer object type 错误,并提供健壮的处理示例。
本文详解如何将 api 返回的 json 字典(而非 json 文件路径)安全、高效地转换为 pandas dataframe,避免 `valueerror: invalid file path or buffer object type` 错误,并提供健壮的处理示例。
当你调用 requests.get() 获取 API 数据后,使用 json.loads(response.text) 得到的是一个 Python 字典(dict)对象;而 pd.read_json() 的设计初衷是读取JSON 格式的字符串、文件路径或类文件对象,它无法直接解析已解码的字典——这正是报错 ValueError: Invalid file path or buffer object type: <class 'dict'> 的根本原因。
✅ 正确做法是:跳过 pd.read_json(),直接用 pd.DataFrame() 构造器初始化 DataFrame。对于单层结构的 JSON 响应(如返回一个包含多个字段的顶层字典),可将其包裹为列表 pd.DataFrame([response_json]);若响应是 JSON 数组(即列表形式的多条记录),则直接传入 pd.DataFrame(response_json) 即可。
以下是修正后的完整示例代码(含错误处理与结构检查):
import pandas as pd
import requests
import json
url = "https://kp.gfz-potsdam.de/app/json/?start=2024-01-01T00%3A00%3A00Z&end=2024-04-21T23%3A59%3A59Z&index=Kp&status=def#kpdatadownload-143"
try:
response = requests.get(url, timeout=10)
response.raise_for_status() # 检查 HTTP 状态码
data = response.json() # 推荐:直接用 .json() 方法替代 json.loads(response.text)
# 关键判断:确认 data 类型并选择合适构造方式
if isinstance(data, dict):
df = pd.DataFrame([data]) # 单条记录 → 转为含 1 行的 DataFrame
elif isinstance(data, list):
df = pd.DataFrame(data) # 多条记录 → 直接构造
else:
raise ValueError(f"Unsupported JSON root type: {type(data)}")
print("DataFrame shape:", df.shape)
print(df.head())
except requests.exceptions.RequestException as e:
print(f"网络请求失败: {e}")
except json.JSONDecodeError as e:
print(f"JSON 解析失败: {e}")
except Exception as e:
print(f"其他错误: {e}")? 注意事项与最佳实践:
- ✅ 优先使用 response.json() 而非 json.loads(response.text),更简洁且自带编码处理;
- ✅ 务必检查 API 响应结构(print(type(data)) 和 print(list(data.keys())[:5])),不同接口返回格式差异大(如嵌套字典、data 字段包裹、分页数组等),需针对性提取;
- ⚠️ 若 JSON 数据深度嵌套(例如 {"results": [{"a":1,"b":2}, ...]}),应先提取有效子列表:df = pd.DataFrame(data["results"]);
- ?️ 生产环境务必添加超时、异常捕获和状态码校验,避免程序因网络或服务端问题中断。
掌握 pd.DataFrame() 对原生 Python 数据结构的直接支持,是高效处理 API 数据的关键——它比强制绕行 read_json 更直观、更可控、也更符合 Pandas 的设计哲学。


















