基于其中一个属性的JSON模式验证
我很难弄清楚如何根据其中一个属性的值验证对象数组。这里有一个JSON对象,如:基于其中一个属性的JSON模式验证,json,validation,jsonschema,Json,Validation,Jsonschema,我很难弄清楚如何根据其中一个属性的值验证对象数组。这里有一个JSON对象,如: { "items": [ { "name": "foo", "otherProperty": "bar" }, { "name": "foo2", "otherProperty2": "baz", "otherProperty3": "baz2
{
"items": [
{
"name": "foo",
"otherProperty": "bar"
},
{
"name": "foo2",
"otherProperty2": "baz",
"otherProperty3": "baz2"
},
{
"name": "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" ] }
}
}
]
}
}
}
}
}
您已经了解了使用enum来区分匹配内容的基本思想,但这里有几个错误:
- Json模式数组没有
,它们有属性
项
- 在这些属性中,您将
定义为一个属性,然后保存其他json模式对象name
- 在模式的第二个分支中定义了
,但在示例中,该属性被称为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" ] }
}
}
]
}
}
}
}
我认为你是在名称中嵌套名称和其他属性。如果你想写一个答案,显示正确的方式,并验证它,那将是非常好的-正如我所说的,在过去几天中,我尝试了很多不同的事情,但没有运气。以上只是最近的一次。