1

I'm trying to build a schema where the statement can be a single dict or a list of dicts. Ex:

{'Document': {'key': 'value'}}

Or multiple keys:

{'Document': [ {'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]}

Following the documentation I tested with this schema:

v.schema = {'Document': {'type': ['dict', 'list'], 'schema': {'type': 'dict'}}}

Here is the output:

>>> v.schema = {'Document': {'type': ['dict', 'list'], 'schema': {'type': 'dict'}}}
>>> v.validate({'Document': [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]})
True
>>> v.validate({'Document': {'key': 'value'} })
False
>>> v.errors
{'Document': ['must be of dict type']}

Test code:

import cerberus

if __name__ == '__main__':
    v = cerberus.Validator()
    v.schema = {'Document': {'type': ['dict', 'list'], 'schema': {'type': 'dict'}}}
    print(v.validate({'Document': [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]}))
    print(v.validate({'Document': {'key': 'value'}}))
    print(v.errors)

The second case the value is a dict type but I get this error instead of getting the schema correctly interpreted.

1 Answers1

0

I think the problem is due to the schema-rule and mapping, if you remove the schema rule it should work like this:

import cerberus

if __name__ == '__main__':
    v = cerberus.Validator()
    v.schema = {'Document': {'type': ['dict', 'list']}}
    print(v.validate({'Document': [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]}))
    print(v.validate({'Document': {'key': 'value'}}))
    print(v.errors)

More info about schema-rule and mapping:

https://docs.python-cerberus.org/en/stable/validation-rules.html#schema-dict

Jayvee
  • 10,670
  • 3
  • 29
  • 40
  • 1
    Hi Jayvee, The trick is that I want to apply a schema to the dict too. So, the solution that you propose works but just don't validate the dict has a schema that I want to apply. – Rafael Koike May 12 '21 at 16:06