互斥 属性 个组
Mutually exclusive property groups
假设我有一个具有四个可能属性的对象:a、b、c、d。 a 和 b 只能一起出现(即当且仅当 b 出现时 a 出现)。如果a和b出现,c不能出现(即a/b和c互斥)。如果 a 和 b 没有出现,c 可能会出现(但不是必须的)。 d 可以与 a/b、c 任意组合出现,也可以单独出现。除 a、b、c 或 d 之外的任何属性都不能出现。
如何将其表示为 jsonschema?我想我可以使用 oneOf
和 required
的某种组合,但我想不出正确的咒语。
您可以将约束表述为:
- 其中之一:
"a"
和 "b"
都存在,"c"
不存在
- 或:
"a"
和 "b"
都不存在。 ("c"
可能存在也可能不存在)
第二点说"neither"有点冗长。这里,我们用allOf
/not
来表示。 (注意:您不能在此处将它们分解为单个 required
子句,因为每个子句都需要一个单独的 not
。)
{
"oneOf": [
{
"required": ["a", "b"],
"not": {"required": ["c"]}
},
{
"allOf": [
{
"not": {"required": ["a"]}
},
{
"not": {"required": ["b"]}
}
]
}
]
}
替代结构
还有一种说法是"neither",其实就是再用oneOf
。由于您必须 恰好传递 oneOf
子句中的一个 ,如果其中一个条目是 {}
(传递所有内容),则所有其他选项都将被禁止。
虽然它稍微简洁一些,但阅读起来可能不太直观:
{
"oneOf": [
{
"required": ["a", "b"],
"not": {"required": ["c"]}
},
{
"oneOf": [
{},
{"required": ["a"]},
{"required": ["b"]}
]
}
]
}
另一种方法是使用架构依赖声明:
"dependencies": {
"c": {
"allOf": [
{
"not": { "required": [ "a" ] }
},
{
"not": { "required": [ "b" ] }
}
]
},
"a": {
"allOf": [
{
"not": { "required": [ "c" ] }
},
{
"required": [ "b" ]
}
]
},
"b": {
"allOf": [
{
"not": { "required": [ "c" ] }
},
{
"required": [ "a" ]
}
]
}
}
假设我有一个具有四个可能属性的对象:a、b、c、d。 a 和 b 只能一起出现(即当且仅当 b 出现时 a 出现)。如果a和b出现,c不能出现(即a/b和c互斥)。如果 a 和 b 没有出现,c 可能会出现(但不是必须的)。 d 可以与 a/b、c 任意组合出现,也可以单独出现。除 a、b、c 或 d 之外的任何属性都不能出现。
如何将其表示为 jsonschema?我想我可以使用 oneOf
和 required
的某种组合,但我想不出正确的咒语。
您可以将约束表述为:
- 其中之一:
"a"
和"b"
都存在,"c"
不存在 - 或:
"a"
和"b"
都不存在。 ("c"
可能存在也可能不存在)
第二点说"neither"有点冗长。这里,我们用allOf
/not
来表示。 (注意:您不能在此处将它们分解为单个 required
子句,因为每个子句都需要一个单独的 not
。)
{
"oneOf": [
{
"required": ["a", "b"],
"not": {"required": ["c"]}
},
{
"allOf": [
{
"not": {"required": ["a"]}
},
{
"not": {"required": ["b"]}
}
]
}
]
}
替代结构
还有一种说法是"neither",其实就是再用oneOf
。由于您必须 恰好传递 oneOf
子句中的一个 ,如果其中一个条目是 {}
(传递所有内容),则所有其他选项都将被禁止。
虽然它稍微简洁一些,但阅读起来可能不太直观:
{
"oneOf": [
{
"required": ["a", "b"],
"not": {"required": ["c"]}
},
{
"oneOf": [
{},
{"required": ["a"]},
{"required": ["b"]}
]
}
]
}
另一种方法是使用架构依赖声明:
"dependencies": {
"c": {
"allOf": [
{
"not": { "required": [ "a" ] }
},
{
"not": { "required": [ "b" ] }
}
]
},
"a": {
"allOf": [
{
"not": { "required": [ "c" ] }
},
{
"required": [ "b" ]
}
]
},
"b": {
"allOf": [
{
"not": { "required": [ "c" ] }
},
{
"required": [ "a" ]
}
]
}
}