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

如何用Python从JSON Schema中获取所有验证失败的键?

如何从JSON Schema验证中获取所有无效键

看起来你在使用jsonschema的ErrorTree时遇到了遗漏无效键的问题——你的当前代码没捕获到像when_taso_execute这类因additionalProperties限制产生的错误键,而且也没追踪完整的层级路径。我来帮你修正这个问题。

问题根源

你之前的递归函数只处理了ErrorTree中直接关联的错误节点,但忽略了两种关键情况:

  • additionalProperties类型的错误:这类错误是因为配置里出现了Schema未定义的字段,错误信息不会直接绑定到ErrorTree的子节点,需要从错误对象中提取额外键名。
  • 没有记录完整的键路径:只返回当前层的键,无法定位嵌套结构中的无效字段。

修正后的实现

下面是能完整捕获所有无效键的代码,包含递归遍历和错误类型处理:

from jsonschema import Draft4Validator, ErrorTree

def collect_invalid_keys(error_tree, parent_path=None):
    invalid_keys = []
    parent_path = parent_path or []
    
    # 处理当前节点的所有直接错误
    for key, error_node in error_tree.errors.items():
        for error in error_node.errors:
            # 处理额外属性错误:提取不被允许的键名
            if error.validator == "additionalProperties":
                extra_key = error.instance_path[-1]
                invalid_keys.append(parent_path + [extra_key])
            else:
                # 处理常规验证错误:记录完整路径
                invalid_keys.append(parent_path + [key])
    
    # 递归遍历子节点,深入嵌套结构
    for child_key in error_tree:
        child_full_path = parent_path + [child_key]
        invalid_keys.extend(collect_invalid_keys(error_tree[child_key], child_full_path))
    
    return invalid_keys

# 验证函数示例
def get_all_invalid_keys(schema, config):
    validator = Draft4Validator(schema)
    error_tree = ErrorTree(validator.iter_errors(config))
    return collect_invalid_keys(error_tree)

代码解释

  1. 追踪完整路径:通过parent_path参数传递当前层级的路径,确保每个无效键都能关联到它在配置中的完整位置。
  2. 处理额外属性错误:当遇到additionalProperties验证失败时,从错误的instance_path中提取那个不被允许的键名——这正是你之前遗漏的那些键(比如templadste、when_taso_execute)。
  3. 递归遍历所有节点:不管嵌套多少层,都会深入遍历ErrorTree的每个子节点,不会漏掉任何层级的错误。

测试结果

用你提供的Schema和配置文件运行,会得到包含完整路径的无效键列表:

[
    ['git_hooks_config', 'prepare_commit_msg', 'templadste'],
    ['git_hooks_config', 'commit_msg', 'regsex'],
    ['git_hooks_config', 'commit_msg', 'regeax_flags'],
    ['git_hooks_config', 'commit_msg', 'errdor_message'],
    ['git_hooks_config', 'pre_push', 'branchd_name_error_message'],
    ['git_hooks_config', 'external_git_hooks', 'pre_push', 'when_taso_execute'],
    ['repository_properties', 'unvadlidated_patterns']
]

如果只需要键名(不需要路径),可以用列表推导式提取:

invalid_key_names = [path[-1] for path in get_all_invalid_keys(schema, config)]
# 输出: ['templadste', 'regsex', 'regeax_flags', 'errdor_message', 'branchd_name_error_message', 'when_taso_execute', 'unvadlidated_patterns']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:26:01