简体   繁体   中英

Cerberus and validating a list containing dicts

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.

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
                            }
                        }
                    }
                }
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM