【发布时间】:2016-08-06 09:45:24
【问题描述】:
我很难弄清楚如何根据其中一个属性的值来验证对象数组。所以我有一个 JSON 对象,例如:
{
"items": [
{
"name": "foo",
"otherProperty": "bar"
},
{
"name": "foo2",
"otherProperty2": "baz",
"otherProperty3": "baz2"
},
{
"name": "imInvalid"
}
]
}
我想说
- items 可以包含 name 可以是“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" ] }
}
}
]
}
}
}
}
}
【问题讨论】:
-
我认为你在 name 中嵌套了 name 和其他属性。
-
如果您想写一个显示正确方法的答案并且它在json-schema-validator.herokuapp.com 上得到验证,那就太好了 - 正如我所说,在过去的几天里我尝试了很多不同的事情,但没有运气。以上只是最新的。
标签: json validation jsonschema