Reputation: 1120
I have an object to define, that needs needs one key or another specific key. Basically a simple or: if(key1 || key2){ -> valid} else {-> invalid}
Now I know of the "require" keyword, but that it isn't able to require keys conditionally as far as I know. In my case I want to exactly key1 or key2 to exists.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "/my_schema",
"type": "object",
"properties": {
"key1": {
"type": "string"
},
"key2": {
"type": "array",
"items": {
"type": "string"
}
},
"key3": {
"type": "array",
"items": {
"type": "string",
"minItems": 1
}
},
"key4": {
"type": "object",
"properties": {
"begin": {
"type": "number"
},
"end": {
"type": "number"
}
}
}
},
"required": [
"key3", "key4"
]
}
If possible, I look for something where I could define an object conditionally like this e.g.:
"required": {
"key1": if(someConditions),
"key2": if(someOtherConditions)
}
or even this:
"porperties":{
"key1":{
"type": someType,
"required": if(someCondition)
}
}
But right now I simply want to make sure that key1 or key2 are required and that the schema is invalid if both are missing.
Upvotes: 0
Views: 415
Reputation: 453
To validate at least one of two attributes must be required, you could use anyOf
blocks like this.
"properties": {...},
"required":[
"key3",
"key4"
],
"anyOf": [
{
"required": [
"key1"
]
},
{
"required": [
"key2"
]
}
]
To validate availability based on some condition you could use if
then
else
keywords. For example,
If key1 = "1", then key2 is required. Otherwise, key3 is required
"if": {
"key1": {
"const": "1" // some simple condition
}
},
"then": {
"required": [
"key2"
]
},
"else": {
"required": [
"key3"
]
}
Upvotes: 1