Advanced Schema Keywords
Learning Focus
Advanced keywords let you build modular, reusable schemas that express complex validation logic without duplication.
Reusable Definitions: $defs and $ref
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$defs": {
"Address": {
"type": "object",
"properties": {
"street": { "type": "string" },
"city": { "type": "string" },
"postal": { "type": "string" }
},
"required": ["city"]
}
},
"type": "object",
"properties": {
"billing": { "$ref": "#/$defs/Address" },
"shipping": { "$ref": "#/$defs/Address" }
}
}
Composition Keywords
allOf — Must match ALL sub-schemas
{ "allOf": [{ "type": "object" }, { "required": ["name"] }] }
anyOf — Must match AT LEAST ONE
{ "anyOf": [{ "type": "string" }, { "type": "number" }] }
oneOf — Must match EXACTLY ONE
{
"oneOf": [
{ "properties": { "type": { "const": "credit" } }, "required": ["cardNumber"] },
{ "properties": { "type": { "const": "bank" } }, "required": ["iban"] }
]
}
Conditional: if / then / else
{
"if": { "properties": { "country": { "const": "US" } } },
"then": { "properties": { "postalCode": { "pattern": "^[0-9]{5}$" } } },
"else": { "properties": { "postalCode": { "pattern": "^[A-Z0-9 -]{3,10}$" } } }
}
Enum and Const
{
"status": { "enum": ["pending", "active", "archived"] },
"currency": { "const": "USD" }
}
Array Constraints
{
"type": "array",
"items": { "$ref": "#/$defs/Product" },
"minItems": 1,
"uniqueItems": true
}
Concept Map
Concept Flow
Schema Composition
├── allOf — AND logic → All sub-schemas must match
├── anyOf — OR logic → At least one must match
├── oneOf — XOR logic → Exactly one must match
├── if/then/else → Conditional validation
└── $ref → Reuse from $defs (DRY)
Common Pitfalls
| Pitfall | Consequence | Prevention |
|---|---|---|
oneOf with overlapping schemas | Validation always fails | Make schemas mutually exclusive |
additionalProperties: false with $ref | Rejects valid properties | Use unevaluatedProperties: false |
Forgetting required in sub-schemas | Fields become optional | Declare required in each sub-schema |
What's Next
- Previous: Schema Introduction — Review the basics.
- Next: JSONPath Querying — Query and extract values from JSON.
- Section Overview — Return to the JSON Schema module index.