为什么此JSON对象针对此JSON模式进行验证?

时间:2018-07-12 19:14:36

标签: json jsonschema

架构:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "oneOf": [
        {
            "if": {
                "properties": {
                    "name": {
                        "const": "alice"
                    }
                }
            },
            "then": {
                "$ref": "#/definitions/alice"
            }
        }
    ],
    "definitions": {
        "alice": {
            "type": "object",
            "properties": {
                "name": {
                    "const": "alice"
                },
                "age": {
                    "type": "number"
                }
            },
            "required": ["name", "age"]
        }
    }
}

对象:

{
  "name": "bob"
}

基本上,我不理解为什么即使名称是bob并且我希望名称是["alice"]之一,JSON对象仍然通过验证。

1 个答案:

答案 0 :(得分:1)

我知道了!事实证明,我只需要在"else": false子句中添加if-then-else,否则即使if失败,该架构仍然可以通过。

像这样:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "oneOf": [
        {
            "if": {
                "properties": {
                    "name": {
                        "const": "alice"
                    }
                }
            },
            "then": {
                "$ref": "#/definitions/alice"
            },
            "else": false
        }
    ],
    "definitions": {
        "alice": {
            "type": "object",
            "properties": {
                "name": {
                    "const": "alice"
                },
                "age": {
                    "type": "number"
                }
            },
            "required": ["name", "age"]
        }
    }
}