Rob
Rob

Reputation: 198

How to express in JSON schema all or none for multiple optional properties?

I want to express that all or none of optional properties are present. For example

{
}  

and

{
    "a" : 1,
    "b" : 2
}  

should be both valid, but

{
    "a" : 1
}  

and

{
    "b" : 2
}  

should be both invalid.

Upvotes: 4

Views: 927

Answers (2)

erosb
erosb

Reputation: 3141

A simpler way:

{
"properties:" {
  "a" : {"type" : "integer"},
  "b" : {"type" : "integer"}
},
"dependencies" : {
  "a" : ["b"],
  "b" : ["a"]
}
}

Upvotes: 5

Rob
Rob

Reputation: 198

Here a schema that satisfies the requirements:

{
    "type": "object",
    "properties": {
        "a": {
            "type": "integer"
        },
        "b": {
            "type": "integer"
        }
    },
    "oneOf": [{
        "required": ["a", "b"]
    }, {
        "not": {
            "anyOf": [{
                "required": ["a"]
            }, {
                "required": ["b"]
            }]
        }
    }],
    "additionalProperties": false
}

An alternative would be to also express in the JSON that the properties belong together like

{
    "parent": {
        "a": 1,
        "b": 2
    }
}

where parent is either present or not and if present, then always has a and b:

{
    "type": "object",
    "properties": {
        "parent": {
            "type": "object",
            "properties": {
                "a": {
                    "type": "integer"
                },
                "b": {
                    "type": "integer"
                }
            },
            "required": ["a", "b"],
            "additionalProperties": false
        }

    },
    "additionalProperties": false
}

Upvotes: 3

Related Questions