Deqing
Deqing

Reputation: 14652

Why is $ref valid under the JSON schema?

I have this schema:

{
    "$schema": "http://json-schema.org/draft-07/schema",
    "definitions": {
        "person": {
          "properties": {
            "name": { "type": "string" }
          }
        },
        "employee": {
            "$ref": "#/definitions/person",
            "properties": {
               "salary": { "type": "number" }
            }
        }
    },
    "properties": {
        "Entry": {
            "$ref": "#/definitions/employee"
        },
    },
}

And surprisingly, the following JSON is valid under the schema:

{
    "Entry": {
        "name": "John",
        "salary": "1234"
    }
}

Can anyone explain how $ref works here? Why is this JSON valid?

-- EDIT --

I found that if I change

"$schema": "http://json-schema.org/draft-07/schema"

to

"$schema": "http://json-schema.org/draft-05/schema"

it will work as expected, but only "draft-05" works; others like "draft-04" "draft-06" are not working.

Upvotes: 0

Views: 268

Answers (1)

Ether
Ether

Reputation: 53996

In JSON Schema versions up to and including draft 7, when the $ref keyword is adjacent to any other keyword, the other keywords are ignored.

You can work around this by enclosing the $ref in an allOf:

...
        "employee": {
            "allOf": [ { "$ref": "#/definitions/person" } ],
            "properties": {
               "salary": { "type": "number" }
            }
        }
    },
...

Upvotes: 2

Related Questions