I'd like to be able to write JSON schema code that allows one property's value to be dependent on the value of another property.
More specifically, I have two questions A and B. Question B's answer can only be not null when question A has a specific answer. If question A does not have that answer, then the value to question B must be null.
E.g.
A: Do you like cars? Yes/No
B: What is your favourite car?
Question B can only be answered if the answer to question A is "Yes", otherwise it must be left null.
After some research I have found this Stack Overflow thread, which describes the enum and if-then-else approaches to answering this question. The enum is very close to what I need and is defined as below:
{
"type": "object",
"properties": {
"foo": { "enum": ["bar", "baz"] },
"bar": { "type": "string" },
"baz": { "type": "string" }
},
"anyOf": [
{
"properties": {
"foo": { "enum": ["bar"] }
},
"required": ["bar"]
},
{
"properties": {
"foo": { "enum": ["baz"] }
},
"required": ["baz"]
}
]
}
In the above, when the value of Foo
is "Bar"
, then the Bar
property is required. Likewise with the value of "Baz"
. However instead of making the property required, I want to be able to change the type of the property from null to string. Or do something to be able to make the answer to B valid.
Any thoughts on this?
Did you consider
Let's take your gist:
If I understand correctly your question, the effect you want to achieve is:
If the respondent likes cars, ask him about favourite car and grab answer, else don't bother with the favourite car (and preferrably force the answer to be null).
As Relequestual correctly ponted out in his comment, JSON Schema makes it hard to 'redefine' type. Moreover, each if-then-else content must be a valid schema on it's own.
In order to achieve this effect, you may want to consider following approach:
Some sample schema (draft07 compliant) which solves your case is listed below. Also some explanations provided below the schema.
Why so complicated?
Because your gist made it so ;-) And more seriously, this is because:
In your gist you define both questions as objects. There might be valid reason behind it, so I kept it that way (however whenever flat list of properties could be used, like "questionA-answer", "questionB-answer" I'd prefer it so to keep schema rules less nested, thus more readable and easy to create).
It seems from your question and gist, that this is important for you that "questionB/answer" is null instead of not being validated against/ignored when it's not relevant, thus I kept it so
Step by step
Questions as objects
Please note, that I've created separate subschemas for "questionA" and "questionB". This is my personal preference and nothing stops you from getting everything inside "definitions" schema of main schema, however I do it usually that way because:
The "propertyNames"
Since we're working here on "type" : "object" I used "propertyNames" keyword to define schema for allowed property names (since classess in programming languages usually have static sets of properties). Try to enter in each object a property outside of this set - schema valdiation fails. This prevents garbage in your objects. Should it be not desired behaviour, just remove "propertyNames" schemas from each object.
"questionB" - where does the trick with changing type sits?
The trick is: do not define property type and other relevant schema rules upfront. Please note how there's no "properties" schema in "questionB" schema. Instead, I used "definitions" to prepare two possible definitions of "answer" property inside "questionB" object. I will use them depending on "questionA" answer value.
"examples" section?
Some objects, that should illustrate how schema works. Play around with answer values, presence of properties etc. Please note, that an empty object will also pass validation, as no property is required (as in your gist) and there's only one dependency - if "questionA" appears, a "questionB" must show up as well.
Ok, ok, top to bottom now, please
Sure. So the main schema can have two properties:
questionA (an object containing property "answer")
questionB (an object containing property "answer")
Is "#/questionA" required? -> No, at least based on your gist.
Is "questionB" required? -> Only if "#/questionA" appears. To add insult to injury :-) the type and allowed values of "#/questionB/answer" strictly depend on the value of "#/questionA/answer".
--> I can safely pre-define main object, foundation for questions objects and will need to define dependency
Please note I am conciously setting relative base reference via "$id" keyword for question sub-schemas to be able to split schema into multiple smaller files and also for read-ability.
--> I can safely pre-define "questionA/answer" property: type, allowed values etc.
Note: I used "definitions" to, well, define schema for specific property. Just in case I'd need to re-use that definition somewhere else... (yep, paranoid about that I am)
--> I can't safely pre-define "#/questionB/answer" property as mentioned above and must do the "trick" part in "#/questionB" sub-schema
NOTE: See "#/definitions/answer-def"? There are two sub-nodes to that, "#/definitions/answer-def/string" and "#/definitions/answer-def/null" . I wasn't entirely sure how I'll do it at the moment, yet I knew I definitely will need that capability of juggle with "#/questionB/answer" property schema in the end.
--> I must define rules for valid combinations of both answers and since "#/questionB/answer" must be always present; I'm doing that in main schema, which uses questions sub-schemas as it's a cap over them that logically makes a good place to define such rule.
So there are those, who like cars - I basically define allowed values of "#/questionA/answer" and relevant definition of property of "#/questionB/answer". Since this is the schema, both sets must match to fulfill this definition. Please note I marked "questionB" property key as required in order to not validate JSON that contains only "questionA" property key against schema.
I did similar thing for those, who don't like cars (how one cannot like cars?! Wicked times...) and at the end I said in "valid-combinations-of-qA-qB": It's either or, people. Either you like cars and give me the answer or you don't like cars and the answer must be null. "XOR" ("oneOf") comes to mind automatically but since I've defined like cars AND answer and doesn't like cars AND answer = null as a complete schemas, logical OR is completely sufficient -> "anyOf".
At the end the finishing touch was to use that rule in "dependencies" section of main schema, which translates to: if "questionA" appears in validated instance, either... or...
Hope it clarifies and helps with your case.
Open questions
Why not use object "answers" with properties reflecting each question answer, with key identifying the question? It could simplify a bit rules and references with regards to dependencies between answers (less typing, yep, I'm a lazy lad).
Why "#/questionB/answer" must be null instead just ignoring it if "#/questionA/answer" : { "enum" : ["No"] } ?
Recommended reading
See "Understanding JSON Schema" : https://json-schema.org/understanding-json-schema/index.html
Some basic examples: https://json-schema.org/learn/
JSON schema validation reference: https://json-schema.org/latest/json-schema-validation.html
A lot of StackOverflow Q&A provides nice insight in how to manage different cases with JSON Schema.
Also it might be helpful at occasion to check for relative JSON Pointers RFC.