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 |
---|---|
Kind | Applicator |
Applies To | Any |
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 |
As if it was set to the (invalid) value:
[]
|
Annotation | None |
Affected By | None |
Affects | None |
Also See |
|
The oneOf
keyword allows you to specify that exactly one of the provided subschemas must validate successfully against a given instance. It ensures that the instance validates against one and only one of the defined subschemas within the oneOf
array. This behavior is akin to a logical “XOR” (exclusive OR) operation, where only one condition needs to be met for validation to pass.
Examples
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"oneOf": [
{
"properties": {
"foo": { "type": "string" }
},
"required": [ "foo" ]
}
]
}
{ "foo": "foo" }
{ "foo": [ "foo" ] }
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"oneOf": [
{
"properties": {
"foo": { "type": "string" }
},
"required": [ "foo" ]
},
{
"properties": {
"bar": { "type": "number" }
},
"required": [ "bar" ]
}
]
}
{ "foo": "foo" }
{ "foo": 33, "bar": "bar" }
{ "foo": "foo", "bar": 33 }
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"oneOf": [
false,
{
"properties": {
"foo": { "type": "string" }
},
"required": [ "foo" ]
}
]
}
{ "foo": "foo" }
{ "foo": false }
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"oneOf": [
true,
{
"properties": {
"foo": { "type": "string" }
},
"required": [ "foo" ]
}
]
}
{ "foo": "foo" }
{ "foo": true }
- Remember, if any subschema within the
oneOf
keyword passes validation or has a booleantrue
value, all the other subschemas withinoneOf
must fail the validation for the overall validation of theoneOf
keyword to be true.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"oneOf": [
{
"oneOf": [
{ "type": "number" }
]
},
{
"oneOf": [
{ "type": "string" }
]
}
]
}
25
"25"
[ "25" ]