oneOf, anyOf, allOf — Schema Composition in JSON Schema
Master JSON Schema composition with oneOf, anyOf, and allOf keywords. Build flexible schemas that validate against multiple sub-schemas for polymorphic data.
Detailed Explanation
Schema Composition Keywords
JSON Schema provides three composition keywords — oneOf, anyOf, and allOf — that combine multiple sub-schemas into flexible validation rules.
anyOf — Match At Least One
The value must validate against one or more of the listed sub-schemas:
{
"payment": {
"anyOf": [
{
"type": "object",
"properties": { "cardNumber": { "type": "string" } },
"required": ["cardNumber"]
},
{
"type": "object",
"properties": { "bankAccount": { "type": "string" } },
"required": ["bankAccount"]
}
]
}
}
A payment object with either a card number or a bank account (or both) is valid.
oneOf — Match Exactly One
The value must validate against exactly one of the listed sub-schemas:
{
"shape": {
"oneOf": [
{
"type": "object",
"properties": {
"type": { "const": "circle" },
"radius": { "type": "number" }
},
"required": ["type", "radius"]
},
{
"type": "object",
"properties": {
"type": { "const": "rectangle" },
"width": { "type": "number" },
"height": { "type": "number" }
},
"required": ["type", "width", "height"]
}
]
}
}
A shape can be a circle or a rectangle, but not both. The const discriminator ensures each branch is mutually exclusive.
allOf — Match Every Sub-Schema
The value must validate against all listed sub-schemas:
{
"allOf": [
{ "$ref": "#/$defs/baseUser" },
{
"type": "object",
"properties": { "role": { "type": "string" } },
"required": ["role"]
}
]
}
This is commonly used with $ref to extend a base schema with additional properties — similar to inheritance in object-oriented programming.
Choosing the Right Keyword
| Keyword | Semantics | Typical use case |
|---|---|---|
anyOf |
At least one matches | Flexible unions, nullable types |
oneOf |
Exactly one matches | Discriminated unions, polymorphic types |
allOf |
All must match | Schema inheritance, mixins |
Generator Behavior
Generators typically do not produce composition keywords from a single sample. These keywords are added manually or generated from multiple samples with different shapes. If you need polymorphic validation, generate schemas for each variant separately and combine them with the appropriate composition keyword.
Use Case
Use composition keywords for polymorphic API responses (different shapes based on type), payment method selection, event systems with varied payloads, or extending base schemas with role-specific fields.
Try It — JSON Schema Generator
Related Topics
$ref and $defs — Reusable Schema Definitions
Advanced Patterns
Enum Values in JSON Schema — Restricting to Allowed Values
Advanced Patterns
Boolean and Null Types in JSON Schema Generation
Basic Types
Array Items Schema — Validating Array Elements
Array Schemas
Generate JSON Schema for REST API Request Bodies
Real-World Schemas