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

Python处理嵌套JSON中的KeyError问题求助

解决方案

1. 修正原代码逻辑问题

原循环存在冗余错误:通过range(len(get_user_function))遍历索引的同时,又在字典推导式里重复遍历整个用户列表,导致生成的字典结构混乱。应直接遍历每个用户项,以name作为目标字典的键。

2. 安全处理字段缺失与位置异常

针对字段缺失或位置偏移的情况,采用dict.get()逐层取值(缺失时返回空值);对于位置异常的字段(比如config_option_12可能不在config层级下),可优先尝试顶层查找,再 fallback 到嵌套层级,或用递归函数全局查找。

基础版优化代码

my_dict = {}

for item in get_user_function:
    # 若name缺失,可选择跳过或用id/索引作为替代键
    name = item.get("name")
    if not name:
        continue
    
    # 安全获取顶层字段,缺失则留空
    user_id = item.get("id", "")
    created = item.get("created", "")
    
    # 处理config_option_12:先查顶层,再查config下,都无则返回空
    config_opt_12 = item.get("config_option_12")
    if not config_opt_12:
        config_opt_12 = item.get("config", {}).get("config_option_12", "")
    
    my_dict[name] = [user_id, created, config_opt_12]

print(my_dict)

进阶版:递归查找任意位置的字段

如果字段位置异常情况复杂(比如config_option_12可能在多层嵌套的任意位置),可以写一个通用递归函数来全局定位:

def find_nested_field(data, target_key):
    """递归查找嵌套字典/列表中的目标字段,找不到返回空值"""
    if isinstance(data, dict):
        if target_key in data:
            return data[target_key]
        for val in data.values():
            res = find_nested_field(val, target_key)
            if res is not None:
                return res
    elif isinstance(data, list):
        for elem in data:
            res = find_nested_field(elem, target_key)
            if res is not None:
                return res
    return ""

# 使用递归函数重构逻辑
my_dict = {}
for item in get_user_function:
    name = item.get("name")
    if not name:
        continue
    
    user_id = item.get("id", "")
    created = item.get("created", "")
    config_opt_12 = find_nested_field(item, "config_option_12")
    
    my_dict[name] = [user_id, created, config_opt_12]

print(my_dict)

核心要点

  • dict.get(key, default):替代直接索引取值,避免KeyError,缺失字段自动返回预设空值。
  • 递归查找函数:适配任意层级的嵌套结构,彻底解决字段位置异常的问题。
  • name缺失处理:可根据业务需求选择跳过项,或用id、循环索引等作为临时键保留数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 18:25:39