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

使用Python调用谷歌翻译API,取JSON中存在的key触发KeyError

问题原因与解决方案

原因

你的JSON响应结构里,detections 是嵌套在 data 这个顶级键下面的,直接访问 result['detections'] 会因为找不到该键抛出KeyError。

修正后的代码

你需要先获取 data 对应的字典,再从中提取 detections:

response = requests.post(url, data=payload, headers=headers)
result = response.json()
print(result['data']['detections'])

额外建议

如果担心响应结构可能有变化,或者想避免键不存在时报错,可以用字典的get()方法做安全访问:

# 若data或detections不存在,返回默认值None
detections = result.get('data', {}).get('detections')
if detections:
    print(detections)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:33:10