Derek Chiang
Derek Chiang

Reputation: 3410

Why does this JSON object validate against this JSON schema?

The schema:

{
    "$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"]
        }
    }
}

The object:

{
  "name": "bob"
}

Basically, I don't understand why even though the name is bob and I want the name to be one of ["alice"], the JSON object still passes the validation.

Upvotes: 1

Views: 29

Answers (1)

Derek Chiang
Derek Chiang

Reputation: 3410

I figured it out! Turns out I just need to add "else": false to the if-then-else clause, or otherwise the schema still passes despite if failing.

So like this:

{
    "$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"]
        }
    }
}

Upvotes: 1

Related Questions