Given a dictionary where the top level keys can be any value, but there is a strict schema within the values of those keys:
{"rand_value": ["key1": "val1", "key2": "val2"], "another_rand_value": ["key1": "val1", "key2": "val2"]}
Can I create a Cerberus schema which will enforce this?
CodePudding user response:
Cerberus must take the field name as a given in order to determine which validation rule applies to it, so you can't do exactly what you're asking. It doesn't have a concept of "top level" rules that apply to the whole document.
You can, however, build a schema "on the fly" based on the actual field names present in the document, then validate against that.
v = cerberus.Validator()
document = {"rand_value": {"key1": "val1", "key2": "val2"},
"another_rand_value": {"key1": "val1", "key2": "val2"}}
fieldschema = {"type": "dict", "keysrules": {"type": "string"}}
v.validate(document, {k: fieldschema for k in document})