Search code examples
validationcerberus

Allow unknown keys but validated values in schema


What is the best way to validate a dict where the keys are unknown but the values have a definite schema. For example:

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

I've tried

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

But this has failed as the validation passes. It should have failed on both the missing must_have_key and the unknown_key. Have I defined something wrong?


Solution

  • You can use the valueschema rule to define rules for abritrary values data in a mapping:

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