如何验证 Cerberus 中的嵌套字典对象
How to validate nested dictionary object in Cerberus
这是一个需要验证的示例数据。 employee_eligibility
嵌套字典中的键是数字字符串“[0-9]+”。
{
"client_id": 1,
"subdomain": "Acme",
"shifts": [
20047, 20048, 20049
],
"employee_eligibility": {
"1": {
"20047": 1,
"20048": 0,
"20049": 1
},
"2": {
"20047": 1,
"20048": 0,
"20049": 1
},
"3": {
"20047": 1,
"20048": 1,
"20049": 0
}
}
}
我编写了以下验证模式:
{
"client_id": {"type": "integer"},
"subdomain": {"type": "string"},
"shifts": {"type": "list", "schema": {"type": "integer"}},
"employee_eligibility": {
"type": "dict",
"keysrules": {"type": "string", "regex": "[0-9]+"},
"schema": {
"type": "dict",
"keysrules": {"type": "string", "regex": "[0-9]+"},
"schema": {"type": "integer"}
}
},
}
当我 运行 验证时出现以下错误:
{'employee_eligibility': ['must be of dict type']}
您的架构略有偏差,您需要使用 valuesrules
来验证字典的值。
schema = {
"client_id": {"type": "integer"},
"subdomain": {"type": "string"},
"shifts": {"type": "list", "schema": {"type": "integer"}},
# `employee_eligibility` is a dictionary
"employee_eligibility": {
"type": "dict",
# the keys in `employee_eligibility` are strings matching this regex
"keysrules": {"type": "string", "regex": "^[0-9]+"},
# the values in `employee_eligibility` are also dictionaries with keys
# that are strings that match this regex and integer values
"valuesrules": {
"type": "dict",
"keysrules": {"type": "string", "regex": "^[0-9]+"},
"valuesrules": {"type": "integer"},
},
},
}
编辑: 添加了一些注释来注释示例
这是一个需要验证的示例数据。 employee_eligibility
嵌套字典中的键是数字字符串“[0-9]+”。
{
"client_id": 1,
"subdomain": "Acme",
"shifts": [
20047, 20048, 20049
],
"employee_eligibility": {
"1": {
"20047": 1,
"20048": 0,
"20049": 1
},
"2": {
"20047": 1,
"20048": 0,
"20049": 1
},
"3": {
"20047": 1,
"20048": 1,
"20049": 0
}
}
}
我编写了以下验证模式:
{
"client_id": {"type": "integer"},
"subdomain": {"type": "string"},
"shifts": {"type": "list", "schema": {"type": "integer"}},
"employee_eligibility": {
"type": "dict",
"keysrules": {"type": "string", "regex": "[0-9]+"},
"schema": {
"type": "dict",
"keysrules": {"type": "string", "regex": "[0-9]+"},
"schema": {"type": "integer"}
}
},
}
当我 运行 验证时出现以下错误:
{'employee_eligibility': ['must be of dict type']}
您的架构略有偏差,您需要使用 valuesrules
来验证字典的值。
schema = {
"client_id": {"type": "integer"},
"subdomain": {"type": "string"},
"shifts": {"type": "list", "schema": {"type": "integer"}},
# `employee_eligibility` is a dictionary
"employee_eligibility": {
"type": "dict",
# the keys in `employee_eligibility` are strings matching this regex
"keysrules": {"type": "string", "regex": "^[0-9]+"},
# the values in `employee_eligibility` are also dictionaries with keys
# that are strings that match this regex and integer values
"valuesrules": {
"type": "dict",
"keysrules": {"type": "string", "regex": "^[0-9]+"},
"valuesrules": {"type": "integer"},
},
},
}
编辑: 添加了一些注释来注释示例