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

