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

Python读取JSON文件提取label字段报TypeError错误如何解决

报错原因

label字段不属于JSON顶层键,它是shapes数组中每个元素的子字段。直接调用data.get("label")会返回None,对None执行循环遍历操作就会触发你遇到的类型错误。

修复方案

如果要读取所有标注的label值,调整遍历逻辑即可,修改后代码如下:

import json

with open("B123.json", mode="r", encoding="utf-8") as f: 
    data = json.load(f)
    # 优先遍历顶层shapes数组,再取每个shape对象的label字段
    for shape in data.get("shapes", []):
        current_label = shape.get("label")
        print(current_label)

补充说明:代码中给get方法设置了默认返回空列表,当JSON不存在shapes字段时也不会触发遍历错误,兼容异常场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 07:57:05