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

如何通过链式key路径访问Python中JSON字典的指定值?

如何通过点分隔路径访问嵌套JSON对象的值?

当然可以实现类似obj[path]的方式访问嵌套JSON中的值,下面是几种实用的实现方法:

方法1:手动拆分路径逐层访问

这是最直观的方式,把路径按.拆分后循环遍历每一层键:

import json

# 加载JSON数据
json_content = '''
{
  "a": {
    "b" : {
      "c" : "value"
    }
  }
}
'''
obj = json.loads(json_content)
path = "a.b.c"

def get_nested_value(target_obj, path_str):
    keys = path_str.split('.')
    current = target_obj
    for key in keys:
        # 检查当前层级是否为字典且包含目标键
        if isinstance(current, dict) and key in current:
            current = current[key]
        else:
            # 路径无效时返回None,也可根据需求抛出异常
            return None
    return current

# 调用示例
print(get_nested_value(obj, path))  # 输出: value

方法2:用functools.reduce简化代码

借助reduce函数可以把循环逻辑简化成一行:

from functools import reduce
import json

obj = json.loads(json_content)
path = "a.b.c"

def get_nested_value(target_obj, path_str):
    try:
        # 依次将每个键作用到当前对象上
        return reduce(lambda current_dict, key: current_dict[key], path_str.split('.'), target_obj)
    except (KeyError, TypeError):
        # 捕获键不存在或中间层级不是字典的异常
        return None

# 调用示例
print(get_nested_value(obj, path))  # 输出: value

方法3:自定义字典类实现obj[path]语法

如果想完全模拟obj[path]的写法,可以继承原生字典类重写__getitem__方法:

import json

class PathAccessibleDict(dict):
    def __getitem__(self, key):
        if isinstance(key, str) and '.' in key:
            keys = key.split('.')
            current = self
            for k in keys:
                current = super().__getitem__(k)
            return current
        # 普通键仍按原生逻辑处理
        return super().__getitem__(key)

# 加载JSON时转换为自定义字典
obj = PathAccessibleDict(json.loads(json_content))

# 直接用点分隔路径访问
print(obj["a.b.c"])  # 输出: value

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 15:45:55