You need to enable JavaScript to run this app. 如何通过jsonpath-ng从嵌套JSON/JSON Schema提取指定层级的键名?
优惠活动
大模型
产品
解决方案
定价
更多

如何通过jsonpath-ng从嵌套JSON/JSON Schema提取指定层级的键名?

报错原因

你遇到的报错、以及之前尝试取键失败,本质是两个逻辑认知偏差:

  • jsonpath_ng返回的DatumInContext对象没有顶层的key属性,IDE弹出的key补全提示是类型推断的误报,并非对象实际提供的运行时接口,运行时自然会抛AttributeError
  • 原本使用的路径表达式tags[*].*,设计作用是匹配节点下的所有值,匹配到的结果是"auth"、"Authentication"这类字符串叶子节点,不是字典对象,本身就没有.keys()方法,自然没法通过这个方式拿到键名。
针对你两个核心需求的可直接运行方案

相比硬套jsonpath表达式绕路取键,先精准定位到目标字典节点、再直接读取节点自身的键是最稳定的写法,完全不需要额外的类型转换。

需求1:提取tags数组内对象的键(预期结果name、description)

from jsonpath_ng import parse
import json

with open("./sample.json", "r") as f:
    json_data = json.load(f)

# 精准匹配tags数组中的每一个对象元素
tag_node_matches = parse("tags[*]").find(json_data)
# 遍历所有匹配到的对象,收集所有键后去重
tag_keys = list({key for match in tag_node_matches for key in match.value.keys()})
print(tag_keys)  # 输出: ['name', 'description']

需求2:提取paths下/rest/auth接口的方法键(预期结果post、get)

# 精准定位到/rest/auth节点,直接读取节点的所有键
auth_node_match = parse("paths./rest/auth").find(json_data)
method_keys = list(auth_node_match[0].value.keys())
print(method_keys)  # 输出: ['post', 'get']

注:jsonpath中带斜杠的路径不需要做转义,直接用点号连接后续的键名即可,解析器会自动把字符串键名和路径片段做映射。

如果必须通过jsonpath匹配直接取键名

如果你不想提前读取节点值,非要从匹配结果的路径信息中提取键名,可以借助match.path中存储的路径片段做解析:

def get_key_from_jsonpath_match(matches):
    extracted_keys = []
    for match in matches:
        # 取当前匹配路径的最后一个片段,即当前节点对应的键名
        last_path_segment = match.path.fields[-1]
        # 过滤掉数组索引、通配符这类非真实键名的片段
        segment_str = str(last_path_segment)
        if not segment_str.startswith("*") and not segment_str.isdigit():
            extracted_keys.append(last_path_segment)
    # 去重返回
    return list(set(extracted_keys))

你之前写的parse("tags[*].*").find(json_data)匹配结果传入这个函数,就能直接返回['name', 'description'],但这种写法的鲁棒性很差,遇到多层嵌套、带特殊字符的键名很容易解析出错。

适配复杂JSON Schema的通用方案

你提到实际处理的是结构复杂的嵌套JSON Schema,这类结构往往深度不定、节点键经常变动,与其反复调整jsonpath表达式,不如用一个通用的递归遍历函数提取指定层级的键:

def extract_dict_keys(obj, target_depth=None, current_depth=0):
    """
    递归提取嵌套结构中的字典键
    :param obj: 待遍历的JSON对象
    :param target_depth: 指定要提取键的层级,None代表提取所有层级的键
    :param current_depth: 当前遍历到的层级,递归内部使用
    """
    collected_keys = set()
    if isinstance(obj, dict):
        if target_depth is None or current_depth == target_depth:
            collected_keys.update(obj.keys())
        for sub_value in obj.values():
            collected_keys.update(extract_dict_keys(sub_value, target_depth, current_depth + 1))
    elif isinstance(obj, list):
        for item in obj:
            collected_keys.update(extract_dict_keys(item, target_depth, current_depth))
    return list(collected_keys)

这个函数不需要硬编码复杂的jsonpath路径,遇到结构变动时不需要反复调整匹配规则,还能通过深度参数精准定位要提取的层级,适配深度嵌套的JSON Schema比硬用jsonpath取键灵活得多。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.25 16:36:04