You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python将无键包裹的JSON API响应转为Pandas DataFrame并追加行

解决方法

核心思路是先把每个IP的响应数据收集到列表里,最后一次性转成DataFrame(比循环追加更高效),同时把请求的IP作为单独字段加入每条数据——因为API返回的JSON里IP是顶级键,不在详情字典中。

完整代码如下:

import requests
import pandas as pd

headers = {
    'accept': 'application/json',
    'Authorization': 'authorization_is_working',
    'Content-Type': 'application/json',
}

ip_list = ["1.2.3.4", "5.6.7.8"]
# 用列表暂存每条数据,后续转DataFrame更高效
data_rows = []

for ip in ip_list:
    try:
        response = requests.get(f'https://.../ip-owner/{ip}', headers=headers)
        # 检查请求是否成功,失败则抛出异常
        response.raise_for_status()
        # 解析JSON响应
        ip_data = response.json()
        # 取出当前IP对应的详情字典
        detail_dict = ip_data[ip]
        # 把IP本身加入字典,作为单独列
        detail_dict['ip_address'] = ip
        # 将处理好的字典加入列表
        data_rows.append(detail_dict)
    except Exception as e:
        print(f"处理IP {ip} 时出错: {str(e)}")
        # 可选:出错时可记录日志或直接跳过

# 把列表转成DataFrame
df = pd.DataFrame(data_rows)
print(df)

关键细节说明:

  • 列表收集数据:循环里直接追加DataFrame会频繁修改对象,效率低下,先存列表再转DF是更优的做法。
  • 提取IP对应详情:API返回的JSON以请求的IP为顶级键,所以用ip_data[ip]就能取出对应的详情字典。
  • 补充IP字段:原详情字典里没有IP信息,手动加入后,DataFrame会多出一列ip_address,方便后续关联查看。
  • 异常处理:加入try-except和response.raise_for_status()可以捕获请求失败(比如404、500)的情况,避免程序直接崩溃。

用你提供的JSON样本测试,最终DataFrame的结构大概是这样:

manager_namemanager_emailregionnamehypervisorproject_nameip_address
joe_smithjoe_smith@abc.comXYZhelloworld.abc.comhello_world1.2.3.4

内容的提问来源于stack exchange,提问作者zadroga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 11:06:25