Reputation: 1421
Say I have some json data like this:
{
"quantity": 3,
"modifiers": [{}]
}
I do not want modifiers
to be present if there is no intent of adding objects into modifiers
.
This should be the correct way if there are no modifiers
:
{
"quantity": 3,
}
and this should be correct with modifiers
:
{
"quantity": 3,
"modifiers": [{
"testing": "some data here"
}]
}
How would I structure the JSON Schema to validate the above-most example to be incorrect?
edit: Example of JSON Schema for the above examples:
{
"type": "object",
"properties": {
"quantity": {
"type": "integer",
"minimum": 1
},
"modifiers": {
"type": "array",
"items": {
"type": "object",
"properties": {
"testing": {
"type": "string"
}
}
},
"minItems": 1
}
},
"required": [
"quantity"
]
}
Upvotes: 2
Views: 1676
Reputation: 24479
You're only missing one thing. Just add "minProperties": 1
at /properties/modifiers/items
.
{
"type": "object",
"properties": {
"quantity": {
"type": "integer",
"minimum": 1
},
"modifiers": {
"type": "array",
"items": {
"type": "object",
"properties": {
"testing": {
"type": "string"
}
},
"minProperties": 1
},
"minItems": 1
}
},
"required": [
"quantity"
]
}
Upvotes: 2
Reputation: 1421
(Draft 7 only) To not allow an array to be empty if present, do this:
"if": {
"required": [
"modifiers"
]
},
"then": {
"properties": {
"modifiers": {
"minItems": 1
}
}
}
This will ensure that this is invalid:
{
"quantity" : 1,
"modifiers":[]
}
However note that the following json would be valid:
{
"quantity" : 1,
"modifiers":[{}]
}
If you don't want that, then make sure to include the appropriate required
field. This would be how the final schema look like based on the given example/schema above:
{
"type": "object",
"properties": {
"quantity": {
"type": "integer",
"minimum": 1
},
"modifiers": {
"type": "array",
"items": {
"type": "object",
"properties": {
"testing": {
"type": "string"
}
},
"required": [
"testing"
]
},
"minItems": 1
}
},
"required": [
"quantity"
],
"if": {
"required": [
"modifiers"
]
},
"then": {
"properties": {
"modifiers": {
"minItems": 1
}
}
}
}
Now, this would also be invalid:
{
"quantity" : 1,
"modifiers":[{}]
}
And this would be valid:
{
"quantity" : 1,
"modifiers":[{"testing":"343"}]
}
Upvotes: 2