我很难弄清楚如何根据其中一个属性的值验证对象数组。所以我有一个 JSON 对象,例如:
{
"items": [
{
"name": "foo",
"otherProperty": "bar"
},
{
"name": "foo2",
"otherProperty2": "baz",
"otherProperty3": "baz2"
},
{
"name": "imInvalid"
}
]
}
我想说的是
- items 可以包含任何对象,其中名称可以是“foo”或“foo2”
- 如果它是“foo”那么唯一有效的其他属性(必需)是
“其他财产”
- 如果名称是“foo2”,则唯一有效的其他名称
属性“otherProperty2”和“otherProperty3”都是必需的
- 除了“foo”和“foo2”之外,“name”的其他值均无效
- 对象本身在 items 数组中是可选的,有些可能会重复。
我尝试了各种各样的事情,但当我验证时,我似乎不会失败。例如,名称“imInvalid”应该会导致验证错误。这是我对架构的最新迭代。我缺少什么?
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"required": ["items"],
"properties": {
"items": {
"type": "array",
"minItems": 1,
"additionalProperties": false,
"properties": {
"name": {
"anyOf": [
{
"type": "object",
"required": ["name", "otherProperty"],
"additionalProperties": false,
"properties": {
"otherProperty": { "type": "string" },
"name": { "enum": [ "foo" ] }
}
},{
"type": "object",
"required": ["name", "otherProperty2", "otherProperty3" ],
"additionalProperties": false,
"properties": {
"otherProperty2": { "type": "string" },
"otherProperty3": { "type": "string" },
"name": { "enum": [ "foo2" ] }
}
}
]
}
}
}
}
}