允许未知键但在架构中验证值

Allow unknown keys but validated values in schema

验证键未知但值具有明确架构的字典的最佳方法是什么。 例如:

data = {
'name': 'test',
'department': {
    'unknown_key': {
        'known_key': 'good',
        'unknown_key': 'bad'
    }
}}

我试过了

schema = {
'name': {
    'type': 'string'
},
'department': {
    'type': 'dict',
    'allow_unknown': {
        'schema': {
            'type': 'dict',
            'schema': {'known_key': {'type': 'string'},
                       'must_have_key': {'type': 'string'}}}
    },
}}

但是由于验证通过,这失败了。它应该在丢失的 must_have_keyunknown_key 上都失败了。我是不是定义错了什么?

您可以使用 valueschema 规则为映射中的任意值数据定义规则:

schema = {
    'name': {'type': 'string'},
    'department': {
        'type': 'dict',
        'valueschema': {
            'type': 'dict',
            'schema':  {
                'known_key': {'type': 'string'},
                'must_have_key': {'type': 'string', 'required': True}
            }
        }
    }
}