json模式,用于验证具有anyOf和oneOf要求的对象数组

时间:2013-11-20 15:50:55

标签: json validation jsonschema

我正在尝试定义一个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子句,则验证失败。第二个数组元素上的相同内容不会引发所需的故障。如何确保针对每个阵列成员运行验证?

1 个答案:

答案 0 :(得分:13)

这是因为你(不小心)使用了“元组输入”。当"items"的值是一个数组,并且它将模式匹配到数组中的特定位置时,就会启用此功能。

如果您将"items"(在您的架构中)更改为架构(而不是架构数组),那么它将以相同的方式验证所有项目。