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

遍历JSON触发KeyError错误,如何避免该问题?

解决JSON遍历中的KeyError问题

遇到部分JSON条目缺少目标键导致的KeyError,可通过以下几种方式解决:

方法一:使用dict.get()方法安全取值

get()方法允许指定键不存在时的默认值,能直接规避KeyError,同时建议直接遍历tasks列表元素而非用索引,更简洁且避免索引越界问题:

for task in data["tasks"]:
    # 获取Assignments,不存在则返回空列表
    assignments = task.get("Assignments", [])
    if assignments:  # 确认列表非空再取第一个元素
        task["Assignments"] = [assignments[0]]
    # 可选:对无Assignments的条目设置默认值
    # else:
    #     task["Assignments"] = []

方法二:用in关键字提前检查键是否存在

先判断目标键是否在字典中,再执行后续操作:

for task in data["tasks"]:
    # 同时检查键存在且对应列表非空,避免IndexError
    if "Assignments" in task and task["Assignments"]:
        task["Assignments"] = [task["Assignments"][0]]

方法三:捕获异常处理(适合少数异常场景)

通过try-except捕获KeyError,同时可一并处理Assignments为空列表时的IndexError:

for task in data["tasks"]:
    try:
        task["Assignments"] = [task["Assignments"][0]]
    except (KeyError, IndexError):
        # 跳过异常条目,或执行其他自定义逻辑
        continue

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:57:10