我已经搜索过,还没有找到解决方案。
我想这样做的架构:
...
"bag": {
"type": "array",
"items": {
"anyOf": [
{"$ref": "#/definitions/obj1"},
{"$ref": "#/definitions/obj2"},
{"$ref": "#/definitions/obj3"}
]
},
"required": ["items"],
"minItems": 1
}
...
使用已定义的对象:
...
"definitions": {
"obj1": {
"type": "object",
"properties": {
"obj1": {
"type": "object",
"properties": {
"a": {
"type": "string"
}
},
"required": ["a"]
}
}
},
"obj2": {
"type": "object",
"properties": {
"obj1": {
"type": "object",
"properties": {
"b": {
"type": "string"
}
},
"required": ["b"]
}
}
},
"obj3": {
"type": "object",
"properties": {
"obj1": {
"type": "object",
"properties": {
"c": {
"type": "string"
}
},
"required": ["c"]
}
}
}
}
...
理想情况下,我想针对如下所示的架构进行验证:
...
"bag": [
{
"obj1": {"a": "test1"}
},
{
"obj3": {"c": "test1"}
}
]
...
在这种情况下,如果有人经过obj1
并obj3
进入bag
。通过模式,obj1
require属性a
和obj3
require property c
。
我在实际执行此操作时遇到了麻烦,因为验证似乎无法正确执行。
有小费吗?提前致谢。
从您当前的模式和示例数据来看,我无法确切地说出您想要什么,而是进行有根据的猜测...
我怀疑您想使用oneOf
而不是anyOf
。
anyOf
允许您匹配多个子方案,看起来您只想允许匹配子方案obj1、2或3。
这将帮助您调试问题,但这不是您始终通过验证的原因。
对于每个定义子模式,您需要添加"additionalProperties": false
。
这是关键:JSON模式是基于约束的,这意味着任何不受约束的内容都是允许的。
additionalProperties
将对象的允许属性限制为properties
(和patternProperties
)中定义的属性。
这是示例架构。您可以在这里看到它与您的实例一起工作:https : //jsonschema.dev/s/MjBUp
{
"$schema": "http://json-schema.org/draft-07/schema",
"definitions": {
"obj1": {
"type": "object",
"properties": {
"obj1": {
"type": "object",
"properties": {
"a": {
"type": "string"
}
},
"required": ["a"]
}
},
"additionalProperties": false
},
"obj2": {
"type": "object",
"properties": {
"obj1": {
"type": "object",
"properties": {
"b": {
"type": "string"
}
},
"required": ["b"]
}
},
"additionalProperties": false
}
},
"type": "array",
"items": {
"anyOf": [
{"$ref": "#/definitions/obj1"},
{"$ref": "#/definitions/obj2"}
]
},
"required": ["items"],
"minItems": 1
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句