In jsonSchema you can indicate whether defined fields are mandatory or not using the "required" attribute:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"header": {
"type": "object",
"properties": {
"messageName": {
"type": "string"
},
"messageVersion": {
"type": "string"
}
},
"required": [
"messageName",
"messageVersion"
]
}
},
"required": [
"header"
]
}
In certain cases, I would like the messageVersion field not to be mandatory. Is there any way to make the mandatory-ness of the this field conditional?
Depending on your situation, there are a few different approaches. I can think of four different ways to conditionally require a field.
Dependencies
The
dependencies
keyword is a conditional variation of therequired
keyword. Foreach property independencies
, if the property is present in the JSON being validated, then the schema associated with that key must also be valid. If the "foo" property is present, then the "bar" property is requiredThere is also a short form if the schema only contains the
required
keyword.Implication
If your condition depends on the value of a field, you can use a boolean logic concept called implication. "A implies B" effectively means, if A is true then B must also be true. Implication can also be expressed as "!A or B". Either the "foo" property does not equal "bar", or the "bar" property is required. Or, in other words: If the "foo" property equals "bar", Then the "bar" property is required
If "foo" is not equal to "bar",
#/anyOf/0
matches and validation succeeds. If "foo" equals "bar",#/anyOf/0
fails and#/anyOf/1
must be valid for theanyOf
validation to be successful.Enum
If your conditional is based on an enum, it's a little more straight forward. "foo" can be "bar" or "baz". If "foo" equals "bar", then "bar" is required. If "foo" equals "baz", then "baz" is required.
If-Then-Else
A relatively new addition to JSON Schema (draft-07) adds the
if
,then
andelse
keywords. If the "foo" property equals "bar", Then the "bar" property is requiredEDIT 12/23/2017: Implication section updated and If-Then-Else section added.