我试图定义一个json模式来限制数组中包含的对象的属性.
到目前为止我所拥有的是:
{
"title":"myCollection","properties":{
"things":{
"type":"array","items":[{
"title":"thingObj","type":"object","properties":{
"name":{
"type":"string"
},"code":{
"type":"string"
},"type":{
"type":"string","enum":["dog","cat"]
},"rate":{
"type":"number"
},"value":{
"type":"number"
}
},"anyOf":[{
"properties":{
"name":{
"type":"string"
}
},"required":["name"]
},{
"properties":{
"code":{
"type":"string"
}
},"required":["code"]
},{
"properties":{
"type":{
"type":"string","enum":["new","existing"]
}
},"required":["type"]
}],"oneOf":[{
"properties":{
"rate":{
"type":"number"
}
},"required":["rate"]
},{
"properties":{
"value":{
"type":"number"
}
},"required":["value"]
}],"additionalProperties":false
}]
}
}
}
现在给出以下jsonobj:
{
"things": [
{
"name": "tabby","code": "meeow","type": "cat","value": 20
},{
"name": "k9","code": "woofer","type": "dog","rate": 15
}
]
}
此json schema validator提供了有效的响应,但此验证似乎仅适用于阵列中的第一个元素.如果删除anyOf子句中包含的所有字段或第一个元素上的oneOf子句,则验证失败.第二个数组元素上的相同内容不会引发所需的故障.如何确保针对每个阵列成员运行验证?
解决方法
这是因为你(不小心)使用了“元组输入”.当“items”的值是一个数组时,它会启用,并且它将模式与数组中的特定位置匹配.
如果将“items”(在模式中)更改为模式(不是模式数组),那么它将以相同的方式验证所有项目.