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

Python中如何仅打印含指定JSON键的数据避免KeyError报错

Python处理JSON时键缺失触发KeyError的解决方法

问题场景

使用Python加载解析JSON数据并打印内容时,JSON结构中并非所有同级条目都包含相同的键,直接通过字典[键名]的方式取值时,遇到不存在的键会抛出KeyError。

待处理JSON结构示例

"rules":[
        {
            "table":"Forest",
            "format":"List",
            "header":{"en":"Forest","fr":"Forêt"},
            "fields":[
                {
                    "name":"Name",
                    "displayName":{"en":"Forest","fr":"Forêt"}
                },
                {
                    "name":"ForestMode",
                    "displayName":{"en":"Forest Mode","fr":"Mode forêt"},
                    "ok":"re.search('Windows(2019|2016)Forest',x) != None",
                    "warn":"re.search('Windows(2012R2|2012)Forest',x) != None",
                    "nok":"re.search('Windows(2008R2|2008|2003|2003Interim|2000)Forest',x) != None",
                    "comment":{"en":"Increase the functional level of the forest","fr":"Augmenter le niveau fonctionnel de la forêt"}
                },
                {
                    "name":"RootDomain",
                    "displayName":{"en":"Root Domain","fr":"Domaine racine"}
                },
                {
                    "name":"Domains",
                    "displayName":{"en":"Domains","fr":"Domaines"}
                },
                {
                    "name":"Sites",
                    "displayName":{"en":"Sites","fr":"Sites"}
                }
            ]
        }
    ]

原有问题代码

import json

with open('./rules-adds.json', 'r') as ad_file:
    ad_data = json.load(ad_file)
    data = ad_data["rules"]

for x in data:
    print(x['table'], x['fields'])
    for y in x['fields']:
        print(y['name'])
        # 直接取ok键,部分条目无该键会报错
        print(y['ok'])

报错信息

print(y['ok'])
KeyError: 'ok'

报错原因:fields数组下的部分元素(比如第一个name为Name的条目)不存在ok键,直接索引取值触发异常。


可用解决方法

所有方法的核心逻辑都是先判断键存在,再执行取值/打印操作,以下是3种最常用的实现:

  • 方法1:用in关键字做键存在性校验
    这是最直观的实现,判断目标键是否在当前字典的键列表中,存在才执行打印:
    for x in data:
        print(x['table'], x['fields'])
        for y in x['fields']:
            print(y['name'])
            # 仅当ok键存在时才打印
            if 'ok' in y:
                print(y['ok'])
    
  • 方法2:用字典内置的get()方法取值
    字典的get(key, default)方法在键不存在时不会抛出异常,会返回指定的默认值(未指定默认值时返回None):
    for x in data:
        print(x['table'], x['fields'])
        for y in x['fields']:
            print(y['name'])
            ok_val = y.get('ok')
            # 取值不为None时才打印
            if ok_val is not None:
                print(ok_val)
    
    如果需要自定义缺失时的返回内容,可以给get传第二个参数,比如y.get('ok', '无对应校验规则')。
  • 方法3:批量处理多个可选键
    如果需要同时处理ok/warn/nok/comment等多个可选键,可以把可选键整理成列表统一遍历判断,减少重复代码:
    # 定义所有需要打印的可选键
    optional_keys = ['ok', 'warn', 'nok', 'comment']
    for x in data:
        print(x['table'], x['fields'])
        for y in x['fields']:
            print(y['name'])
            for k in optional_keys:
                if k in y:
                    print(f"{k}: {y[k]}")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 09:12:29