Reputation: 187
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']}
Upvotes: 1
Views: 5219
Reputation: 71
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.
Upvotes: 3
Reputation: 92854
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
{}
Upvotes: 0