Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 399
Christopher J. Wright Avatar asked Oct 16 '25 18:10

Christopher J. Wright


1 Answers

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}
            }
        }
    }
}
like image 100
funky-future Avatar answered Oct 19 '25 11:10

funky-future