I have two types defined by a JSON Schema:
Type A
{
"type": "object",
"properties": {
"a": { "type": "string" }
}
}
Type X
{
"type": "object",
"properties": {
"x": { "type": "string" }
}
}
I want to create a schema combining A and X, but without additional properties. (only properties 'a' and/or 'x' should be present). I tried to use "allOf" but I can't add a restriction about additional properties. If I add "additionalProperties" in A or X, it doesn't work.
How should I process ? Of course, I don't want to repeat A into X
CodePudding user response:
What you're looking for is the unevaluatedProperties
feature available in jsonschema 2019-09 upwards. In contrast to additionalProperties
, which only concerns the locally defined properties, unevaluatedProperties
works across sub-schemas (but is more expensive to evaluate).
The schema
{
"anyOf": [
{
"type": "object",
"properties": {
"a": {
"type": "string"
}
}
},
{
"type": "object",
"properties": {
"x": {
"type": "string"
}
}
}
],
"unevaluatedProperties": false
}
Allows
{
"a": "foo",
"x": "bar"
}
But disallows
{
"a": "foo",
"x": "bar",
"t": "baz"
}
If you're stuck with an earlier jsonschema version, you have to manually define the properties of the sub-schemas in the parent like this:
{
"anyOf": [
{
"type": "object",
"properties": {
"a": {
"type": "string"
}
}
},
{
"type": "object",
"properties": {
"x": {
"type": "string"
}
}
}
],
"properties": {
"a": true,
"x": true
},
"additionalProperties": false
}