1

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']}
Night Str
  • 127
  • 2
  • 10

2 Answers2

3

I tried the following and it seems to be working fine:

'oneof':[
     {
         'type': 'dict',
         'schema':{
             'field1': {
                 'type':'string',
                 'required':True
             },
             'field2': {
                 'type':'string',
                 'required':False
             }
         }
     },
     {
         'type': 'list',
         'schema': {
             'type': 'dict',
             'schema':{
                 'field1': {
                     'type':'string',
                     'required':True
                 },
                 'field2': {
                     'type':'string',
                     'required':False
                 }
             }
         }
     }
]

For anyone else who comes across this, I am hoping this might be useful. Took me some time to understand things completely.

Reza Rahemtola
  • 1,182
  • 7
  • 16
  • 30
  • Hopefully, now everything should be good. I provided an answer which is working for me (the answer is generic and should be working for the use case asked in the question). Thanks for the resources Shree. – Vaibhav Chaddha Jul 23 '21 at 06:02
0

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
{}
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • 1
    Thank for the answer but it is does not exactly what i need. Data may be bouth any: `{'v': {'name': 'test'}}` or `{'v': [{'name': 'test1'}, {'name': 'test2'}...]}` – Night Str Jul 23 '19 at 05:07