Search code examples
pythonvalidationcerberus

Cerberus: superfluous nesting in the error object


I use cerberus for validate my data, like:

document = {
    "region": 77,
    "drivers": {
        "data": [
            { "birthday": "2004-01-01", "kbm_class": "3", "driving_experience": 10 },
            { "birthday": "1988-01-01", "kbm_class": "3", "driving_experience": 10 }],
        "type": "limited" 
    },
    "engine_power": 80,
    "is_taxi": False
}

and i use scheme like:

schema = {
    'engine_power': {'type': 'integer'},
    'region':  {'type': 'integer'},
    'is_taxi': {'type': 'boolean'},
    'drivers': {
        'schema': {
            'type': {'type': 'string'},
            'data': {
                'type': 'list',
                'schema': {
                    'type': 'dict',
                    'schema': {               
                        'birthday': {'type': 'string', 'validator': validate_age},
                        'kbm_class': {'type': 'string'},
                        'driving_experience': {'type': 'integer'}
                    }
                }
            }
        }
    }
}

When I get an error object, it has too much nesting: Cerberus creates a list for each level of nesting:

{'drivers': [{'data': [{0: [{'birthday': ['driver too young']}]}]}]}

Can i get something like:

{'drivers': {'data': [{'birthday': ['driver too young']}]}}

Solution

  • Using cerberus==0.9.2 you get a slimmer error response like this:

    {'drivers': {'data': {0: {'birthday': 'driver too young'}, 3: {'birthday': 'driver too young'}}}}
    

    You cannot get rid of the indexes because they are important to show which items from the list contains errors.