作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有多个模式,每个模式都用于数据子类型:
type_one = {
"type": "object",
"properties": {
"one": "string"
}
}
type_two = {
"type": "object",
"properties": {
"one": "string",
"two": "string"
}
}
我想要的是检查传入数据是“type_one”还是“type_two”或抛出错误。像这样:
general_type = {
"type": [type_one, type_two]
}
我的传入数据是这样的:
{
"one": "blablabla",
"two": "blebleble",
...
}
我已经测试了几种方法但没有成功...有什么想法吗?谢谢
最佳答案
您可以在您的对象架构中使用属性 "additionalProperties": False
以仅允许一组确切的键。
首先,让我们拥有有效的模式结构:
type_one = {
"type": "object",
"additionalProperties": False,
"properties": {
"one": {"type": "string"}
}
}
type_two = {
"type": "object",
"additionalProperties": False,
"properties": {
"one": {"type": "string"},
"two": {"type": "string"}
}
}
general_type = {
"type": [type_one, type_two]
}
注意:您问题的架构是"one": "string"
,它应该是"one": {"type": "string"}
这是我们的输入数据:
data_one = {
"one": "blablabla"
}
data_two = {
"one": "blablabla",
"two": "blablabla"
}
这是验证:
import validictory
# additional property 'two' not defined by 'properties' are not allowed
validictory.validate(data_two, type_one)
# Required field 'two' is missing
validictory.validate(data_one, type_two)
# All valid
validictory.validate(data_one, type_one)
validictory.validate(data_two, type_two)
validictory.validate(data_one, general_type)
validictory.validate(data_two, general_type)
希望对您有所帮助。
关于Python Validictory(JSON 模式验证): How to OR multiple schemas?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16852846/
我是一名优秀的程序员,十分优秀!