3

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?

dreftymac
  • 31,404
  • 26
  • 119
  • 182

1 Answers1

2

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}
            }
        }
    }
}
funky-future
  • 3,716
  • 1
  • 30
  • 43
  • How to define `valuerules` (a new name for `valueschema`) for a dict type, where are the top-level key names are unknown? – zaufi Aug 04 '21 at 01:12