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

Python AWS环境下如何提取JSON对象深层嵌套的指定字段值

AWS Rekognition TextDetection嵌套字段提取正确实现方式

错误原因

你使用的语法不符合Python字典的访问规则,存在两个核心问题:

  • Python中访问嵌套字典需要逐层通过[]取值,不能将多层键封装在同一个方括号内
  • Geometry字段和DetectedText是同级字段,均为TextDetections列表元素的直接子属性,你错误将DetectedText作为Geometry的父级字段,会导致找不到对应键

正确实现

场景1:确认返回结构完整无缺失

直接逐层提取字段即可,参考完整循环示例:

# 假设response是AWS服务返回的JSON转成的Python字典对象
for item in response["TextDetections"]:
    # 首层字段提取
    detected_text = item["DetectedText"]
    text_type = item["Type"]
    confidence = item["Confidence"]
    # 嵌套字段提取
    bounding_box = item["Geometry"]["BoundingBox"]
    left = bounding_box["Left"]
    # 其他BoundingBox字段同理
    top = bounding_box["Top"]
    width = bounding_box["Width"]
    height = bounding_box["Height"]

如果只需单独取Left值,简写为:
left = item["Geometry"]["BoundingBox"]["Left"]

场景2:避免字段缺失抛出KeyError

使用字典的get()方法,逐层设置默认兜底值:

left = item.get("Geometry", {}).get("BoundingBox", {}).get("Left", 0.0)

当任意一层键不存在时,会直接返回默认值0.0,不会中断程序运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 09:45:05