pboettch / json-schema-validator

JSON schema validator for JSON for Modern C++
Other
470 stars 135 forks source link

Override default value of referenced schema #189

Closed martin-koch closed 1 year ago

martin-koch commented 2 years ago

Let us assume that we have a schema like this one:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "title": "A rectangle",
    "properties": {
        "width": {
            "$ref": "#/definitions/length",
        "default": 20
        },
        "height": {
             "$ref": "#/definitions/length"
        }
    },
    "definitions": {
         "length": {
          "type": "integer",
           "default": 10
        }
    },
    "additionalProperties": false,
    "type": "object"
}

In my point of view I would expect that the default value of the concrete instance is considered instead of the default used by the referenced schema. With the current implementation the validated and patched output of an empty json will be

{"height":10,"width":10}

while I would have expected it to be

{"height":10,"width":20}

I will suggest a change via a pull-request if you are okay with this.

pboettch commented 2 years ago

I understand your approach. Overriding values "imported" by a $ref sounds like a good idea, but is forbidden by draft7: https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-01#section-8.3

All other properties in a "$ref" object MUST be ignored.

Having said that, default is special as it has no meaning in the standard other then being there. Validation are free to use it in any sensible way - more or less.

Do you know whether in later json-schema-standards using $ref with overriding keywords is allowed?

martin-koch commented 2 years ago

It seems that is allowed since Draft2019. From the current draft:

Several keywords can be used to reference a schema which is to be applied to the current instance location. "$ref" and "$dynamicRef" are applicator keywords, applying the referenced schema to the instance.

There is also an example with overridden default values in the draft where it states:

Feature A will therefore use a default value of true, while Feature B will use the generic default value of null. (...) Note that there are other reasonable approaches that a different application might take. For example, an application may consider the presence of two different values for "default" to be an error, regardless of their schema locations.'

pboettch commented 2 years ago

OK. Let's go see your PR.