如何在JSON解析循环中处理字段缺失导致的报错问题
Python 嵌套JSON空值取值报错解决方案
你遇到的报错是因为当JSON中style字段为None时,直接尝试下标访问['name']会触发TypeError: 'NoneType' object is not subscriptable,以下是两种可直接落地的解决方案:
方案1:极简单行替换(适合仅单个字段需要处理的场景)
直接将报错的那行代码替换为以下代码即可实现你要的iferror效果,取不到值时默认返回DoesNotExist:
(t["vintage"]["wine"]["style"] or {}).get("name", "DoesNotExist")
逻辑说明:如果
style为None,or {}会将值转为空字典,再通过字典的get方法取值,不存在对应键就返回预设的默认值,同时兼容style存在但无name键的场景。
方案2:通用安全取值函数(适合多嵌套字段需要做空校验的场景)
如果后续还有多个类似的嵌套取值场景,可以封装一个通用的安全取值函数复用:
def safe_get(nested_obj, keys_path, default="DoesNotExist"): current = nested_obj for key in keys_path: try: current = current[key] except (KeyError, TypeError): return default return current
调用时只需传入取值的键路径即可:
safe_get(t, ["vintage", "wine", "style", "name"])
修改后的完整代码示例
results = [ ( t["vintage"]["wine"]["winery"]["name"], t["vintage"]["year"], t["vintage"]["wine"]["id"], f'{t["vintage"]["wine"]["name"]} {t["vintage"]["year"]}', t["vintage"]["wine"]["statistics"]["ratings_average"], t["vintage"]["wine"]["statistics"]["ratings_count"], t["price"]["amount"], t["vintage"]["wine"]["region"]["name"], (t["vintage"]["wine"]["style"] or {}).get("name", "DoesNotExist"), ) for t in r.json()["explore_vintage"]["matches"] ]
内容的提问来源于stack exchange,提问作者Scott
相关产品推荐
相关产品推荐

