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

Python3访问JSON列表深层嵌套元素遇KeyError问题求助

解决深层嵌套JSON的KeyError问题及代码优化建议

核心问题原因

出现KeyError: "config_option_12"是因为部分条目的config字典里不存在config_option_12键,或者该键对应的层级结构不完整(比如存在config_option_12但缺失config_option_12.1)。

直接解决方法

1. 使用字典get()方法(快速修改现有代码)

get()方法允许指定键不存在时的默认值,避免抛出KeyError。对于深层嵌套,可链式调用get():

修改你的字典推导式:

my_dict = {
    item["name"]: [
        item["id"], 
        item["created"], 
        # 若config_option_12不存在,返回空字典作为默认值
        item["config"].get("config_option_12", {})
    ] 
    for item in get_user_function
}

如果需要提取更深层级的字段(比如config_option_12.1.1),继续链式get():

my_dict = {
    item["name"]: [
        item["id"], 
        item["created"], 
        # 逐层设置默认值,确保每一层缺失时不会报错
        item["config"]
            .get("config_option_12", {})
            .get("config_option_12.1", {})
            .get("config_option_12.1.1", False)
    ] 
    for item in get_user_function
}

2. 编写通用嵌套取值函数(适合频繁处理深层结构)

如果需要多次提取不同的深层字段,写一个复用函数更高效:

def get_nested_value(data, key_chain, default=None):
    """
    从嵌套字典中安全取值
    :param data: 原始嵌套字典
    :param key_chain: 键的列表,比如["config", "config_option_12", "config_option_12.1", "config_option_12.1.1"]
    :param default: 键不存在时返回的默认值
    """
    current = data
    for key in key_chain:
        current = current.get(key, default)
        if current == default:
            break
    return current

# 使用示例
my_dict = {
    item["name"]: [
        item["id"], 
        item["created"], 
        get_nested_value(item, ["config", "config_option_12"], {})
    ] 
    for item in get_user_function
}

3. 异常捕获(适合需要针对性处理缺失条目的场景)

如果需要对缺失字段的条目做特殊处理(比如记录日志),可以用try-except:

my_dict = {}
for item in get_user_function:
    try:
        nested_val = item["config"]["config_option_12"]["config_option_12.1"]["config_option_12.1.1"]
    except KeyError:
        # 可添加日志记录缺失条目的信息
        nested_val = False  # 设置默认值
    my_dict[item["name"]] = [item["id"], item["created"], nested_val]

代码优化建议

  1. 避免全局变量:get_user_function作为全局变量会持续占用内存,建议在需要时调用get_users(),或用functools.lru_cache装饰器缓存结果(注意确保返回的JSON数据可哈希)。
  2. 添加请求异常处理:原get_users()函数未处理请求失败的情况,建议补充:
import requests

def get_users():
    url = "https://blablabla/api/users"
    headers = {"Authorization": accessToken, "Content-Type": "application/json", "Accept": "application/json"}
    try:
        r = requests.get(url, headers=headers, timeout=10)
        r.raise_for_status()  # 抛出HTTP错误(如404、500)
        return r.json()
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")
        return []
  1. 排查缺失数据:先统计缺失字段的条目数量,确认数据问题:
missing_config_12 = sum(1 for item in get_user_function if "config_option_12" not in item["config"])
print(f"共有{missing_config_12}条数据缺失config_option_12字段")
  1. 分批处理大数据:如果响应包含数万个条目,一次性加载到内存可能导致性能问题,可考虑流式处理(若API支持分页)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 18:50:27