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
相关产品推荐
相关产品推荐

