如何使一组多个互斥属性中的任何一个除外 [英] How to make anyOf a set of multually exclusive properties except one
问题描述
我有一个旧的API,我正在尝试在JSON模式中定义,并且该对象具有一个怪异的结构,其中有一组4个属性,其中任何一个都是必需的,而其中3个是互斥的.之后还有30多个共享的可选属性,我将它们记为...
.
I have a legacy API I'm trying to define in a JSON Schema and the object has a weird structure where there are a set of 4 properties, any one of them is required, and 3 of them are mutually exclusive. The are a more than 30 shared optional properties after that as well, I'll note them as ...
.
例如
{ "foo": "bar", "baz": 1234, ... } // OK
{ "foo": "bar", "buzz": 1234, ... } // OK
{ "foo": "bar", "fizz": 1234, ... } // OK
{ "foo": 1234, ... } // OK
{ "baz": 1234, ... } // OK
{ ... } // NOT OK
{ "baz": 1234, "buzz": 1234, ... } // NOT OK
我可以做一个oneOf
,但是不允许foo
与其他对象一起出现,anyOf
允许baz
,buzz
和fizz
彼此出现,是不可能的.
I could do a oneOf
but that doesn't allow foo
to be present with the others, anyOf
allows for baz
,buzz
, and fizz
to be present with each other which is not possible.
我试图定义如下内容:
{
"type": "object",
"properties": {
"foo": {"type": "string"},
"baz": {"type": "number"},
"buzz": {"type": "number"},
"fizz": {"type": "number"}
},
"anyOf": [
{"required": ["foo"]},
{"required": [{"oneOf": [
{"required": ["baz"]},
{"required": ["buzz"]},
{"required": ["fizz"]}
]}
]}
]
}
和
{
"type": "object",
"properties": {
"foo": {"type": "string"},
"baz": {"type": "number"},
"buzz": {"type": "number"},
"fizz": {"type": "number"}
},
"anyOf": [
{"required": ["foo"]},
{"oneOf": [
{"required": ["baz"]},
{"required": ["buzz"]},
{"required": ["fizz"]}
]
}
]
}
但是这不起作用,我只是对json模式了解得还不够,还不知道这是否可能.
But that does not work and I just don't know enough about json schema yet to know if this possible.
推荐答案
有趣!可能会有更整洁的解决方案,但我们开始...
Interesting! There might be a neater solution, but here we go...
可以通过禁止属性的成对组合来表示互斥"约束:
The "mutually exclusive" constraint can be expressed by banning pairwise combinations of the properties:
{
"not": {
"anyOf": [
{"required": ["baz", "buzz"]},
{"required": ["buzz", "fizz"]},
{"required": ["fizz", "baz"]}
]
}
}
至少一个"约束条件可以用anyOf
表示:
The "at least one of" constraint can be expressed with anyOf
:
{
"anyOf": [
{"required": ["foo"]},
{"required": ["baz"]},
{"required": ["buzz"]},
{"required": ["fizz"]}
}
}
如果仅将这两个约束组合到一个模式中,则它应该起作用:
If you just combine these two constraints into a single schema, then it should work:
{
"not": {"anyOf": [...]},
"anyOf": ...
}
这篇关于如何使一组多个互斥属性中的任何一个除外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!