首页 > 解决方案 > 使用 Cerberus 验证具有严格模式的任意 dict 键

问题描述

我正在尝试验证 JSON,其模式指定具有任意字符串键的 dicts 列表,其对应的值是具有严格模式的 dicts(即,内部 dict 的键严格是一些字符串,这里是 'a' )。从 Cerberus 文档中,我认为我想要的是“keysrules”规则。文档中的示例似乎只显示了如何使用“keysrules”来验证任意键,而不是它们的值。我写了下面的代码作为例子;我能做的最好的就是假设“keysrules”将支持“模式”参数来定义这些值的模式。

keysrules = {
    'myDict': {
        'type': 'dict',
        'keysrules': {
            'type': 'string',
            'schema': {
                'type': 'dict',
                'schema': {
                    'a': {'type': 'string'}
                }
            }
        }
    }
}


keysRulesTest = {
    'myDict': {
        'arbitraryStringKey': {
            'a': 'arbitraryStringValue'
        },
        'anotherArbitraryStringKey': {
            'shouldNotValidate': 'arbitraryStringValue'
        }
    }
}


def test_rules():
    v = Validator(keysrules)
    if not v.validate(keysRulesTest):
        print(v.errors)
        assert(0)

这个例子确实验证了,我希望它不在'shouldNotValidate'上验证,因为那个键应该是'a'。'keysrules' 所暗示的灵活性(即,由'keysrules' 管理的键除了{'type': 'string'} 之外没有其他约束)递归地向下传播到它下面的所有模式?还是我犯了一些不同的错误?我怎样才能达到我想要的结果?

标签: pythoncerberus

解决方案


我不想要keysrules,我想要valuesrules:

keysrules = {
    'myDict': {
        'type': 'dict',
        'valuesrules': {
            'type': 'dict',
            'schema': {
                    'a': {'type': 'string'}
            }
        }
    }
}


keysRulesTest = {
    'myDict': {
        'arbitraryStringKey': {
            'a': 'arbitraryStringValue'
        },
        'anotherArbitraryStringKey': {
            'shouldNotValidate': 'arbitraryStringValue'
        }
    }
}


def test_rules():
    v = Validator(keysrules)
    if not v.validate(keysRulesTest):
        print(v.errors)
        assert(0)

这产生了我想要的结果。


推荐阅读