Is it possible to set up a JSON schema that still allows for additionalProperties
but does not match if a very particular property name is present? In other words, I need to know if it's possible to have the exact opposite of the required
declaration.
Schema:
{
"type": "object",
"properties": {
"x": { "type": "integer" }
},
"required": [ "x" ],
"ban": [ "z" ] // possible?
}
Match:
{ "x": 123 }
Match:
{ "x": 123, "y": 456 }
Do not match:
{ "x": 123, "y": 456, "z": 789 }
What you want to do can be achieved using the not
keyword. If the not
schema validates, the parent schema will not validate.
{
"type": "object",
"properties": {
"x": { "type": "integer" }
},
"required": [ "x" ],
"not": { "required": [ "z" ] }
}
There is a simpler approach. Define that if x is present it must not satisfy any schema. By reduction to absurdity x can not be present:
{
"properties" : {
"x" : {
"not" : {}
}
}
}
I solved the issue by banning additional properties via "additionalProperties": false
but using patternProperties
to allow any property name except the banned one.
{
"type": "object",
"properties": {
"x": { "type": "integer" }
},
"required": [ "x" ],
"patternProperties": {
"^(?!^z$).*": {}
},
"additionalProperties": false
}
To specify the absence of a field, you can expect it's type to be null
.
{
"type": "object",
"properties": {
"x": { "type": "integer" },
"z": { "type": "null" }
},
"required": [ "x" ]
}