Search code examples
pythonvalidationdictionarycerberus

How to validate by cerberus the data the field of which can be a dict, or list of dict?


I need to validate dictionary received from a user

the problem is that a field can be both dictionary and list of dictionaries. How i can validate that with cerberus?

Like a example i try this schemas:

v = Validator(
    {
        'v': {
            'type': ['dict', 'list'], 
            'schema': {
                'type': 'dict', 
                'schema': {'name': {'type': 'string'}}
           }
       }
    }
)

But when I try it on a test data, I receive error:

v.validate({'v': {'name': '2'}})  # False
# v.errors: {'v': ['must be of dict type']}

Error:

{'v': ['must be of dict type']}

Solution

  • I guess the inner schema is for defining types and rules either for values of a dict keys if v is a dict:

    v = Validator(
        {
            'v': {
                'type': ['dict', 'list'],
                'schema': {
                    'name': {'type': 'string'}
               }
           }
        }
    )
    
    print(v.validate({'v': {'name': '2'}}))
    print(v.errors)
    

    OR for list values if v is a list:

    v = Validator(
        {
            'v': {
                'type': ['dict', 'list'],
                'schema': {
                    'type': 'integer',
               }
           }
        }
    )
    
    print(v.validate({'v': [1]}))
    print(v.errors)
    

    Positive output for both cases:

    True
    {}