Michael Hagar
Michael Hagar

Reputation: 646

Appropriate behavior of JSON schema for nested required properties?

Say I have a JSON schema like this:

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "myKey": {"$ref": "myKey.json#"}
    },
    "additionalProperties": false
}

and then somewhere else I have myKey.json:

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object"
    "properties": {
        "A": {
            "type": "array",
            "description": "Array of stream object IDs",
            "items": { "type": "integer" }
        },
        "B": {
            "type": "array",
            "description": "Array of stream object IDs",
            "items": {"type": "integer" }
        }
    },
    "required": ["A", "B"],
    "additionalProperties": false
}

The important thing here is that inside myKey, there are two required properties, but myKey itself is not required. Does the fact that myKey have required properties propagate up to the top so that myKey is forced to become required? In other words, which of these two objects, if any, ought to be validated by this schema?

{
  "name": "myName",
}

{
  "name": "myOtherName",
  "myKey": 
   {
     "A": [1, 2]      // Note that B is missing
   }
}

Upvotes: 1

Views: 585

Answers (1)

jruizaranguren
jruizaranguren

Reputation: 13605

The first one is valid according to the schema and the second one no.

The way to read properties tag is: if this property key is found, then it must satisfy this schema.

{
  "name": "myName"
}

For the object above, myKey is not required so it satisfies the schema.

{
  "name": "myOtherName",
  "myKey": 
   {
     "A": [1, 2]      // Note that B is missing
   }
}

For the second object, myKey is present, so it must satisfy the schema of that property. But it is not satisfied because it should have both A and B properties.

The same idea is applied to every level. The following object satisfies the schema:

{
    "name": "myOtherName",
    "myKey": 
    {
        "A": [],
        "B": []
    }
}

But this does not:

{
    "name": "myOtherName",
    "myKey": 
    {
        "A": [],
        "B": ""
    }
}

Upvotes: 2

Related Questions