0

我有以下 JSON 验证

var schema = {
    "type": "object",
    "required": ["name", "profession"],
    "properties": {
        "name": { "type": "string" },
        "profession": {
            "oneOf": [
                { "$ref": "#/definitions/developer" },
                { "$ref": "#/definitions/manager" }
            ]
        }
    },
    "definitions": {
        "developer": {
            "type": "object",
            "properties": {
                "jobLevel": { "$ref": "#/definitions/jobLevels" },
                "linesOfCode": { "type": "number" },
                "languages": { "enum": ["C++", "C", "Java", "VB"] }
            },
            "required": ["jobLevel"]
        },
        "manager": {
            "type": "object",
            "properties": {
                "jobLevel": { "$ref": "#/definitions/jobLevels" },
                "peopleManaged": { "type": "number" },
                "responsibilities": {
                    "type": "array",
                    "minItems": 1,
                    "items": "string",
                    "uniqueItems": true
                }
            },
            "required": ["jobLevel"]
        },
        "jobLevels": { "enum": ["Beginner", "Senior", "Expert"] }
    }
}

我尝试使用上述验证字符串验证以下 JSON 字符串。

 var validate = ajv.compile(schema);
 var valid = validate({
     "name": "David",
     "profession": {
         "jobLevel": "Expert",
         "linesOfCode": 50000,
         "languages": "Java"
     },
 });

在这里,我收到消息“data.profession 应该与 oneOf 中的一个模式完全匹配”,尽管我在数据中只提供了一个具有正确实例变量等的实例。你能告诉我我在这里做错了什么吗?顺便说一下,我使用了 AJV 验证器。

谢谢你。

4

1 回答 1

1

The problem here is that the object for profession object is valid according to both schemas inside oneOf keyword, and the spec requires that it is valid against exactly one schema: https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#oneof

The reason for it being valid according to both schemas is because additional properties are allowed.

You can:

  • use anyOf (it would be faster in 50% of cases, as it will stop validation when the 1st schema succeeds)
  • use additionalProperties: false to disallow additional fields
于 2016-10-20T21:02:46.567 回答