如何用Python检查JSON中指定key是否存在?现有代码报KeyError
解决方案
你的代码触发KeyError的原因是:当child键不存在时,直接通过i['fields']['customfield_11723']['child']访问会因为键不存在抛出异常。以下是三种可行的解决方法:
方法1:用in关键字检查键存在性
先获取customfield_11723对应的字典对象,再判断'child'是否在其中,避免提前访问不存在的键:
for i in todos['issues']: custom_field = i['fields']['customfield_11723'] if 'child' in custom_field: print("True")
方法2:使用字典get()方法安全取值
get()方法在键不存在时会返回None(或你指定的默认值),不会抛出异常:
for i in todos['issues']: child = i['fields']['customfield_11723'].get('child') if child is not None: print("True")
如果需要兼容customfield_11723本身也可能不存在的场景,可以嵌套使用get():
for i in todos['issues']: custom_field = i.get('fields', {}).get('customfield_11723', {}) if 'child' in custom_field: print("True")
方法3:用try-except捕获异常
通过捕获KeyError处理键不存在的情况,适合需要区分不同异常场景的需求:
for i in todos['issues']: try: # 尝试访问child键,存在则执行打印 _ = i['fields']['customfield_11723']['child'] print("True") except KeyError: # 键不存在时跳过或执行其他逻辑 pass
内容的提问来源于stack exchange,提问作者Nir Eyal
相关产品推荐
相关产品推荐

