我很难弄清楚如何根据其中一个属性的值来验证对象数组。所以我有一个JSON对象,如:
{
"items": [
{
"name": "foo",
"otherProperty": "bar"
},
{
"name": "foo2",
"otherProperty2": "baz",
"otherProperty3": "baz2"
},
{
"name": "imInvalid"
}
]
}
我想说的是
我尝试了各种各样的事情但是当我验证时我似乎无法失败。例如,名称“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" ] }
}
}
]
}
}
}
}
}
答案 0 :(得分:8)
您已经掌握了使用枚举来区分匹配内容的基本想法,但这里有一些错误:
otherProperty3
,但在您的示例中,该属性被称为anotherProperty3
试试这个稍微修改过的版本:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"required": ["items"],
"properties": {
"items": {
"type": "array",
"minItems": 1,
"additionalProperties": false,
"items": {
"anyOf": [
{
"type": "object",
"required": ["name", "otherProperty"],
"additionalProperties": false,
"properties": {
"otherProperty": { "type": "string" },
"name": { "enum": [ "foo" ] }
}
},{
"type": "object",
"required": ["name", "otherProperty2", "anotherProperty3" ],
"additionalProperties": false,
"properties": {
"otherProperty2": { "type": "string" },
"anotherProperty3": { "type": "string" },
"name": { "enum": [ "foo2" ] }
}
}
]
}
}
}
}