if : Schema
if
SchemaThis keyword declares a condition based on the validation result of the given schema.
| Value |
This keyword must be set to a valid JSON Schema
Hint: Use the jsonschema metaschema and jsonschema lint commands to catch keywords set to invalid values
|
|---|---|
| Kind | Applicator |
| Applies To | Any |
| Base Dialect | 2019-09 |
| Changed In | None |
| Introduced In | Draft 7 |
| Vocabulary | Applicator |
| Specification | https://json-schema.org/draft/2019-09/draft-handrews-json-schema-02#rfc.section.9.2.2.1 |
| Metaschema | https://json-schema.org/draft/2019-09/meta/applicator |
| Official Tests | draft2019-09/if-then-else.json |
| Default | None |
| Annotation | None |
| Affected By | None |
| Affects |
|
| Also See |
|
The if keyword introduces a subschema whose evaluation result restricts instances to validate against the then or else sibling subschemas (if present). Note that the evaluation outcome of this subschema controls which other subschema to apply (if any) but has no direct effect on the overall validation result.
Best Practice
The if,
then, and else keywords can be thought of as imperative variants
of the anyOf keyword, and both
approaches are equally capable of describing arbitrary conditions. Choose the
one that more elegantly describes your desired
constraints.
Digging Deeper
This keyword has no effect if neither the then nor else keywords are declared within the same subschema.
However, when collecting annotations, the JSON Schema implementation will still
need to evaluate the if keyword in
case its subschema emits annotations.
The
if
,
then
, and
else
keywords are equivalent to the ? and : ternary
conditional operators found in most programming languages. For example:
bool valid = if_schema ? then_schema : else_schema;
JSON Schema is a constraint-driven language. Therefore, omitting either the then or the else keywords is equivalent to setting the corresponding part of the ternary conditional operation to the boolean true. In other words, undefined consequent or alternative paths lead to success. For example:
// If `then` is missing
bool valid = if_schema ? true : else_schema;
// If `else` is missing
bool valid = if_schema ? then_schema : true;
Examples
{
"$schema": "https://json-schema.org/draft/2019-09/schema",
"if": { "multipleOf": 2 },
"then": { "minimum": 0 },
"else": { "exclusiveMaximum": 0 }
}10-27-3"Hello World"{
"$schema": "https://json-schema.org/draft/2019-09/schema",
"if": { "multipleOf": 2 },
"then": { "minimum": 0 }
}10-27-3{
"$schema": "https://json-schema.org/draft/2019-09/schema",
"if": { "multipleOf": 2 },
"else": { "minimum": 0 }
}10-27-3{
"$schema": "https://json-schema.org/draft/2019-09/schema",
"if": { "items": { "type": "string" } }
}[ "foo", "bar", "baz" ]{ "keyword": "/if/items", "instance": "", "value": true }[ 1, 2, 3 ]