Cerberus and validating a list containing dicts

445 views Asked by At

I'm trying to validatie the following doc.

document = {
            'days': {
                'Monday': [{
                    'address': 'my address',
                    'city': 'my town'
                }],
                'Tuesday': [{
                    'address': 'my address',
                    'city': 'my town'
                }]
            }
        }

Using the following schema.

    schema = {
                'days': {
                    'type': 'dict',
                    'allowed': ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
                    'schema': {
                        'type': 'list',
                        'schema': {
                            'address': {
                                'type': 'string'
                            },
                            'city': {
                                'type': 'string', 'required': True
                            }
                        }
                    }
                }
            }
v = Validator(schema)
if not v.validate(document, schema):
  raise Exception("Configuration file is not valid", v.errors)

I get the following error: {days: ['must be of dict type']}

I cannot figure out how to validate the dict that is contained within the list.

1

There are 1 answers

0
Tim Roberts On BEST ANSWER

You were very close. You can use valuesrules to say "whatever the keys are, here's the rules for the values". Then, in the list, you need a schema that says the list has dicts, then a schema inside that for the elements. There may be a simpler way to do it, but this passes your document.

schema = {
            'days': {
                'type': 'dict',
                'allowed': ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
                'valuesrules': {
                    'type': 'list',
                    'schema': {
                        'type': 'dict',
                        'schema': {
                            'address': {
                                'type': 'string'
                            },
                            'city': {
                                'type': 'string', 'required': True
                            }
                        }
                    }
                }
            }
        }