我想验证解析为Python字典的JSON对象,如下所示:
# example with 2 elements
{
'coordinates': [-20.3, 30.6]
}
# example with 3 elements
{
'coordinates': [-20.3, 30.6, 0]
}
到目前为止,我已经能够定义以下架构:
schema = {
'coordinates': {
'required': True,
'type': 'list',
'minlength': 2,
'maxlength': 3,
'schema': {
'type': 'float',
},
}
}
我还想检查以下约束:
coordinates
字段值的第一项应该在-30.0和10.0之间但是我无法提出有用的东西。有没有人建议如何实现这一目标?
更新:根据已接受的答案,架构变为以下内容
schema = {
'coordinates': {
'required': True,
'type': 'list',
"oneof_items": (
({"min": -30.0, "max": 10.0}, {"min": -10.0, "max": 50.0}),
({"min": -30.0, "max": 10.0}, {"min": -10.0, "max": 50.0}, {}),
),
}
}
docs:https : //docs.python-cerberus.org/en/stable/validation-rules.html#of-rules-typesaver
添加此规则:
{"oneof_items":
(
({"min": -30.0, "max": 10.0}, {"min": -10.0, "max": 50.0}),
({"min": -30.0, "max": 10.0}, {"min": -10.0, "max": 50.0}, {}),
)
}
这使得与长度相关的规则变得多余。为了摆脱冗余,Python对象引用或规则集注册表是可行的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句