JSON 架构:有条件地要求 属性 取决于多个属性的值
JSON Schema: Conditionally require property depending on several properties' values
我想使用 JSON 模式验证 JSON 文件,根据其他一些属性的值,应该 需要 几个“属性”。
例子
- 具有属性“A”、“B”、“C”和“D”
- 如果“A”的值为“foo”,则需要 C
- 如果“B”的值为“foo”,则需要 D
- 如果“A”和“B”都具有值“foo”,则 C 和 D 都是必需的
- 否则,不需要任何内容
我在这里看到了一个非常有用的答案: --> 在那里,作者解决了如何解决单个 属性(例如,只有“A”具有值“foo”,因此需要“C”)。
但是,我目前看不到如何将这个答案扩展到我的案例,其中有几个属性决定了结果。
示例文件
为了说明,我提供了一些应该通过或未通过验证的文件:
应该通过:
{
"A": "bar"
"B": "baz"
}
{
"A": "foo"
"C": "some value"
}
{
"A": "bar"
"B": "foo"
"D": "some value"
}
应该失败:
{
"A": "foo"
"B": "foo"
"D": "some value"
}
您可以通过多种方式组合条件,但将它们与 allOf
组合通常是最好的方式。
{
"type": "object",
"properties": {
"A": {},
"B": {},
"C": {},
"D": {}
},
"allOf": [
{ "$ref": "#/definitions/if-A-then-C-is-required" },
{ "$ref": "#/definitions/if-B-then-D-is-required" }
],
"definitions": {
"if-A-then-C-is-required": {
"if": {
"type": "object",
"properties": {
"A": { "const": "foo" }
},
"required": ["A"]
},
"then": { "required": ["C"] }
},
"if-B-then-D-is-required": {
"if": {
"type": "object",
"properties": {
"B": { "const": "foo" }
},
"required": ["B"]
},
"then": { "required": ["D"] }
}
}
}
我想使用 JSON 模式验证 JSON 文件,根据其他一些属性的值,应该 需要 几个“属性”。
例子
- 具有属性“A”、“B”、“C”和“D”
- 如果“A”的值为“foo”,则需要 C
- 如果“B”的值为“foo”,则需要 D
- 如果“A”和“B”都具有值“foo”,则 C 和 D 都是必需的
- 否则,不需要任何内容
我在这里看到了一个非常有用的答案:
但是,我目前看不到如何将这个答案扩展到我的案例,其中有几个属性决定了结果。
示例文件
为了说明,我提供了一些应该通过或未通过验证的文件:
应该通过:
{
"A": "bar"
"B": "baz"
}
{
"A": "foo"
"C": "some value"
}
{
"A": "bar"
"B": "foo"
"D": "some value"
}
应该失败:
{
"A": "foo"
"B": "foo"
"D": "some value"
}
您可以通过多种方式组合条件,但将它们与 allOf
组合通常是最好的方式。
{
"type": "object",
"properties": {
"A": {},
"B": {},
"C": {},
"D": {}
},
"allOf": [
{ "$ref": "#/definitions/if-A-then-C-is-required" },
{ "$ref": "#/definitions/if-B-then-D-is-required" }
],
"definitions": {
"if-A-then-C-is-required": {
"if": {
"type": "object",
"properties": {
"A": { "const": "foo" }
},
"required": ["A"]
},
"then": { "required": ["C"] }
},
"if-B-then-D-is-required": {
"if": {
"type": "object",
"properties": {
"B": { "const": "foo" }
},
"required": ["B"]
},
"then": { "required": ["D"] }
}
}
}