Reputation: 4620
I want to validate a json key presence, only if another key exists AND equals some value.
For instance, on the following json I want the presence of "baz" only if "key" equals "foo":
{
"id":"myid",
"key":"foo",
"baz":"baz!"
}
I can validate it simply using following json schema (draft 4):
{
"properties":
{
"key":{
"type": "string",
"enum": ["foo", "bar"]
},
"baz":{
"type": "string"
},
"quuz":{
"type": "string"
}
},
"anyOf":
[
{
"properties":{
"key":{ "enum": ["foo"] }
},
"required": ["baz"]
},
{
"properties":{
"key":{ "enum": ["bar"] }
},
"required": ["quuz"]
}
]
}
The following json is valid as well:
{
"id":"myid",
"key":"bar",
"quuz":"quuz!"
}
This is not valid ("key" = "bar" requires "quuz"):
{
"id":"myid",
"key":"bar",
"baz":"baz!"
}
So far, so good. Now: I need the json being valid also if the "key" key is missing:
{
"id":"myid"
}
This just does not work with the above schema, because the "anyOf" keyword sets the "required" fields.
Is it possible to get a "anyOf or missing key" behavior?. Draf
Any help?
Upvotes: 1
Views: 1817
Reputation: 4062
You can implement that logic by describing two exclusive subschemas, with and without key
:
{
"properties":
{
"key":{
"type": "string",
"enum": ["foo", "bar"]
},
"baz":{
"type": "string"
},
"quuz":{
"type": "string"
}
},
"oneOf":
[
{
"not": {"required": ["key"]}
},
{
"required": ["key"],
"anyOf": [
{
"properties":{
"key":{ "enum": ["foo"] }
},
"required": ["baz"]
},
{
"properties":{
"key":{ "enum": ["bar"] }
},
"required": ["quuz"]
}
]}
]
}
Upvotes: 3