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

Python解析API返回JSON时出现KeyError,如何正确引用嵌套字段?

KeyError报错修复方案

错误原因

  • Python原生字典不支持用"product.buybox_winner.seller.name"这种带点的字符串直接访问嵌套层级的键,必须逐层访问对应层级的键
  • 接口返回的JSON结构中,buybox_winner下不存在seller字段,卖家信息存储在空字符串键""下
  • availability.in_stock返回值为布尔类型false(对应Python的False),你用字符串"False"做判断永远不会命中

正确实现代码

基础写法(确认返回结构固定时使用)

# set up the request parameters
params = {
  'api_key': 'XXXXXXXXXXXXXXXXXXXXXXXXX',
  'type': 'product',
  'item_id': 'XXXXXXXXX',
  'url': 'https://www.somestore.com',
  'output': 'json'
}

# make the http GET request to the API
api_result = requests.get('https://api.shopperapi.com/request', params)
product_data = json.loads(api_result.text)

# 逐层访问嵌套键
buybox_winner = product_data["product"]["buybox_winner"]
seller_name = buybox_winner[""]["name"]
in_stock = buybox_winner["availability"]["in_stock"]

if seller_name == "MyStore.com" and not in_stock:
    my_Mailer("Its out of stock")

安全兼容写法(避免中间字段缺失时报错)

如果不能保证接口返回的所有字段都存在,可以用字典的get方法设置默认值,避免触发KeyError:

product = product_data.get("product", {})
buybox_winner = product.get("buybox_winner", {})
seller_info = buybox_winner.get("", {})
seller_name = seller_info.get("name")
in_stock = buybox_winner.get("availability", {}).get("in_stock")

if seller_name == "MyStore.com" and in_stock is False:
    my_Mailer("Its out of stock")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 16:36:02