How to handle default values of sub-objects within a JSON schema validation?

2.1k views Asked by At

How should a JSON schema validator handle the case where a sub-object of an object has a default value but the parent object hasn't?

Imagine the following schema

{
    "type": "object",
    "properties": {
        "element": {
           "type": "object",
           "properties": {
               "number" : { "type": "integer", "default": 15 }
           }
        }
    }
}

Validated against the following JSON: {} it is resulting in {}.

But shouldn't it result in

{
    "element": {
        "number": 15
    }
}

.

How do we have to interpret the default-keyword? I read the corresponding lines in the standard, but they haven't helped me further.

2

There are 2 answers

2
awwright On BEST ANSWER

The act of validating an instance only returns "valid" or "invalid". JSON Schema validation doesn't change the instance in any way, or "result in" a new instance.

"default" is a fairly generic metadata keyword that can (and is allowed to) mean different things to different people. It doesn't necessarily mean that you can fill in values when they don't exist. It does mean, at the very least, that you can assume an initial value at the time you decide to create it.

Like "title" and "description", the "default" keyword is mostly aimed at user interfaces.

4
Trojan On

Good question..

But there is a simple solution for it.You can use enum keyword for default values.See the below example that can give you the snapshot of it

  filterType: {
            type: 'String',
            required: true,
            enum: ["Accounts", "portfolios"]
        }

so that field should contain any of those two value..i think this would work for you...