The
if
keyword is used to conditionally apply a subschema based on whether a certain condition is met. It allows you to define different validation rules depending on whether an instance satisfies a condition or not. The validation outcome of this keyword’s subschema has no direct effect on the overall validation result. Rather, it controls which of the
then
or
else
keywords are evaluated.
If an instance passes the validation against the
if
subschema, then it must also be validated against the
then
subschema, if present.
If an instance fails the validation against the
if
subschema, then it must also be validated against the
else
subschema, if present.
This keyword is meaningless without
then
and
else
.
The annotations are collected from this keyword’s subschema in the usual way, irrespective of whether
then
and
else
are present or not.
Examples
"$schema"
:
"https://json-schema.org/draft/2020-12/schema"
,
"type"
:
"object"
,
"properties"
:
{
"role"
:
{
"enum"
:
[
"HOD"
,
"professor"
]
},
"HOD_Id"
:
{
"type"
:
"integer"
},
"professor_Id"
:
{
"type"
:
"integer"
}
"if"
:
{
"properties"
:
{
"role"
:
{
"const"
:
"HOD"
}
"then"
:
{
"required"
:
[
"HOD_Id"
]
},
"else"
:
{
"required"
:
[
"professor_Id"
]
}
Want to learn even more JSON Schema?
The authors of this website are writing a book (
Unifying Business, Data, and Code
) that covers, for the first time in print, topics like:
Writing your own JSON Schema vocabularies
Understanding JSON Schema annotations
Hosting your own JSON Schema registries
More importantly, our book teaches you a methodology for effective data management that will transform how you think about data.
Read it online on
O'Reilly
, or buy it from
Amazon
and
eBooks.com
.
Need help? Have questions?
Learning JSON Schema is often confusing, we all went through that. But don't worry, we are here to help! You can start a thread on
GitHub Discussions
, chat with us on
Slack
, or come talk to us at our live
Office Hours
. We are friendly! :)
Hint:
Your question might have been already answered before in
GitHub Discussions
. Might be worth double-checking before submitting a new one.