anyOf : Array<Schema>
anyOf
Array<Schema>An instance validates successfully against this keyword if it validates successfully against at least one schema defined by this keyword’s value.
Value | This keyword must be set to a non-empty array, where each item is a valid JSON Schema |
---|---|
Kind | Applicator |
Applies To | Any |
Base Dialect | 2020-12 |
Changed In | None |
Introduced In | Draft 4 |
Vocabulary | Applicator |
Specification | https://json-schema.org/draft/2020-12/json-schema-core.html#section-10.2.1.2 |
Metaschema | https://json-schema.org/draft/2020-12/meta/applicator |
Official Tests | draft2020-12/anyOf.json |
Default | None |
Annotation | None |
Affected By | None |
Affects | None |
Also See |
|
The anyOf keyword restricts instances to validate against at least one (but potentially multiple) of the given subschemas. This keyword represents a logical disjunction (OR) operation, as instances are valid if they satisfy the constraints of one or more subschemas (the union of the constraints).
Digging Deeper
Keep in mind that when collecting annotations, the JSON Schema implementation will need to exhaustively evaluate every subschema past the first match instead of short-circuiting validation, potentially introducing additional computational overhead.
For example, consider 3 subschemas where the instance validates against the first. When not collecting annotations, validation will stop after evaluating the first subschema. However, when collecting annotations, evaluation will have to proceed past the first subschema in case the others emit annotations.
This keyword is equivalent to the ||
operator found in most programming
languages. For example:
bool valid = A || B || C;
As a reference, the following boolean truth table considers the evaluation result of this keyword given 3 subschemas: A, B, and C.
anyOf |
Subschema A | Subschema B | Subschema C |
---|---|---|---|
Invalid | Invalid | Invalid | Invalid |
Valid | Invalid | Invalid | Valid |
Valid | Invalid | Valid | Invalid |
Valid | Invalid | Valid | Valid |
Valid | Valid | Invalid | Invalid |
Valid | Valid | Invalid | Valid |
Valid | Valid | Valid | Invalid |
Valid | Valid | Valid | Valid |
Examples
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"anyOf": [
{ "required": [ "foo" ] },
{ "required": [ "bar" ] }
]
}
{ "foo": 1 }
{ "bar": 2 }
{ "foo": 1, "bar": 2 }
{ "extra": 4 }
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"anyOf": [
{ "title": "Branch #1", "type": "number" },
{ "title": "Branch #2", "type": "string" },
{ "title": "Branch #3", "type": "integer" }
]
}
3.14
{ "keyword": "/anyOf/0/title", "instance": "", "value": [ "Branch #1" ] }
12345
{ "keyword": "/anyOf/0/title", "instance": "", "value": [ "Branch #1" ] }
{ "keyword": "/anyOf/2/title", "instance": "", "value": [ "Branch #3" ] }
{ "foo": 1 }