oneOf : Array<Schema>
oneOf
Array<Schema>An instance validates successfully against this keyword if it validates successfully against exactly 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
Hint: Use the jsonschema metaschema command to catch keywords set to invalid values
|
---|---|
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.3 |
Metaschema | https://json-schema.org/draft/2020-12/meta/applicator |
Official Tests | draft2020-12/oneOf.json |
Default | None |
Annotation | None |
Affected By | None |
Affects | None |
Also See |
|
The oneOf keyword restricts instances to validate against exactly one (and only one) of the given subschemas and fail on the rest. This keyword represents a logical exclusive disjunction (XOR) operation. In practice, the vast majority of schemas don’t require exclusive disjunction semantics but a simple disjunction. If you are not sure, the anyOf keyword is probably a better fit.
Common Pitfall
Avoid this keyword unless you absolutely need exclusive disjunction semantics, which is rarely the case. As its name implies, this keyword enforces the instance to be valid against only one of its subschemas. Therefore, a JSON Schema implementation will exhaustively evaluate every subschema to make sure the rest fails, potentially introducing unnecessary computational overhead.
This keyword is equivalent to the following complex boolean construct that
combines the ||
, &&
, and !
operators found in most programming languages:
bool valid = (A && !B && !C) || (!A && B && !C) || (!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.
oneOf |
Subschema A | Subschema B | Subschema C |
---|---|---|---|
Invalid | Invalid | Invalid | Invalid |
Valid | Invalid | Invalid | Valid |
Valid | Invalid | Valid | Invalid |
Invalid | Invalid | Valid | Valid |
Valid | Valid | Invalid | Invalid |
Invalid | Valid | Invalid | Valid |
Invalid | Valid | Valid | Invalid |
Invalid | Valid | Valid | Valid |
Examples
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"oneOf": [
{ "required": [ "foo" ] },
{ "required": [ "bar" ] },
{ "required": [ "baz" ] }
]
}
{ "foo": 1 }
{ "bar": 2 }
{ "foo": 1, "bar": 2 }
{ "foo": 1, "bar": 2, "baz": 3 }
{ "extra": 4 }