JSON & Schema
JSON Schema oneOf vs anyOf vs allOf
oneOf requires exactly one matching branch, anyOf requires at least one, and allOf requires every branch. The difference matters most when branches overlap.
Published
Quick comparison: oneOf, anyOf and allOf
| Keyword | Required matches | Typical use |
|---|---|---|
| oneOf | Exactly one | Distinct variants |
| anyOf | One or more | Overlapping accepted shapes |
| allOf | Every branch | Combine constraints |
oneOf: exactly one schema must match
A value that matches zero branches fails. A value that matches two branches also fails, so distinguish object variants with required fields, const, or non-overlapping constraints.
anyOf: one or more may match
anyOf succeeds after at least one branch matches; matching several branches is valid.
allOf: every schema must match
allOf intersects constraints. It does not merge schemas by rewriting them and can interact with closed-object rules in non-obvious ways.
Objects with required, const or enum
{
"oneOf": [
{ "required": ["email"], "properties": { "kind": { "const": "email" } } },
{ "required": ["phone"], "properties": { "kind": { "const": "phone" } } }
]
}What a generator can and cannot infer
- A sample can reveal structure and observed types.
- A sample cannot prove whether variants are exclusive.
- Business discriminators and allowed alternatives require deliberate schema design.
Try the example
Validate exactly one contact variant
Const discriminators keep the email and phone branches mutually distinguishable.
oneOf: EmailContact | PhoneContactExpected result: The email object matches exactly one branch.
Try the example
Allow overlapping anyOf branches
A positive integer satisfies both number and integer constraints and remains valid under anyOf.
anyOf: [number >= 0, integer]Expected result: The value 4 is valid even though it matches both branches.
Build the base first
Generate the shared structure
Infer the common fields, then add and validate the composition rule explicitly.