Skip to main content

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

PitfallConsequencePrevention
oneOf with overlapping schemasValidation always failsMake schemas mutually exclusive
additionalProperties: false with $refRejects valid propertiesUse unevaluatedProperties: false
Forgetting required in sub-schemasFields become optionalDeclare required in each sub-schema

What's Next