JSON Schema 2020-12 is a dialect built from vocabularies. Declare it with $schema, use an absolute $id, and reuse schemas through $defs and $ref. Use prefixItems for tuple slots, items for the tail, unevaluatedProperties to close objects across allOf, dependentRequired or dependentSchemas for fields, and contains with minContains for arrays. Treat format and content keywords as annotations by default.
- $schema selects the dialect and its vocabularies; $id sets the base URI, so relative references resolve differently when a schema is moved or embedded.
- prefixItems describes positional tuple slots while items constrains the remaining elements; contains with minContains and maxContains counts matches.
- additionalProperties only sees properties declared in the same schema object; unevaluatedProperties also sees annotations from adjacent applicators such as allOf, $ref, and if/then/else.
- In 2020-12, $ref is an applicator, so sibling keywords apply; draft-07 ignored them, which is the migration change most likely to alter validation results.
- format, contentEncoding, and contentMediaType are annotations by default; decode and validate content in application code instead of treating them as security checks.
JSON Schema 2020-12 is not draft-07 with a few extra keywords. It is a dialect assembled from vocabularies, and that design explains most of its behavior. $schema chooses the vocabularies, $id establishes the base URI, and keywords such as unevaluatedProperties work by collecting annotations from other keywords. Code that treats a schema as a flat checklist will misread it, and a validator that silently ignores an unknown vocabulary will pass documents the author expected to fail.
The practical payoff is precision. Tuples, conditional fields, closed objects, and counted array matches can be expressed without custom code. The cost is that correctness now depends on the dialect being declared, the references being resolvable, and the validator actually implementing the keywords. This guide covers the parts that change production behavior and the mistakes that survive code review.
A dialect assembled from vocabularies
A meta-schema defines which vocabularies a schema uses and whether each is required. The 2020-12 meta-schema enables core, applicator, unevaluated, validation, meta-data, format-annotation, and content. Format assertion is a separate vocabulary whose support is optional. A validator may support only some of them, and the specification allows that as long as unsupported vocabularies are not silently treated as mandatory.
This is why $schema is not decoration. It identifies the dialect, selects the keyword semantics, and tells the validator which meta-schema to check against. A document without $schema is interpreted using the implementation's default, which may be draft-07, 2019-09, or 2020-12 depending on the library and version. In a polyglot repository, that default is not a contract.
Adoption is now broad enough to plan around. OpenAPI 3.1 uses JSON Schema 2020-12 as the basis for its Schema Object, so API teams encounter the dialect even when they never write a standalone schema. Library support still varies by keyword, especially for unevaluatedProperties, unevaluatedItems, and dynamic references, so the validator matrix matters as much as the specification.
$schema, $id, and reference resolution
$schema belongs at the root of a schema resource and uses the exact URI https://json-schema.org/draft/2020-12/schema. It is an identifier, not a fetch instruction. A validator should already know that dialect; it should not download the meta-schema on every validation. Embedded schema resources may declare their own $schema when they use a different dialect, but mixing dialects in one document is an advanced technique that deserves tests.
$id identifies a schema resource and sets the base URI for relative references. In 2020-12 it must resolve to an absolute URI, and it must not contain a non-empty fragment. The old draft-07 habit of putting a plain-name fragment in $id is replaced by $anchor. A subschema with its own $id is a distinct resource, so moving that subschema to another file or nesting it elsewhere can change how every relative $ref inside it resolves.
References are identifiers, not promises of network availability. The core specification explicitly says implementations should not assume they can fetch a network-addressable URI. Production systems should bundle referenced schemas at build time, register them in the validator, and fail the build on a dangling or duplicate identifier. A request-time fetch turns DNS, latency, and availability into validation failures.
$defs and $ref: composition without surprises
$defs is a standard place to store reusable schemas. It applies no constraints by itself; a definition only matters when something references it. $ref is an applicator: it applies the referenced schema to the current instance location. In 2020-12, other keywords can appear alongside $ref in the same schema object and they are applied. That is a deliberate change from draft-07, where a reference object ignored its siblings.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://api.example.com/schemas/order.json",
"type": "object",
"properties": {
"id": { "type": "string" },
"shipTo": { "$ref": "#/$defs/address" },
"lines": {
"type": "array",
"minItems": 1,
"items": { "$ref": "#/$defs/lineItem" }
}
},
"required": ["id", "shipTo", "lines"],
"$defs": {
"address": {
"type": "object",
"properties": {
"street": { "type": "string" },
"city": { "type": "string" },
"country": { "type": "string", "pattern": "^[A-Z]{2}$" }
},
"required": ["street", "city", "country"]
},
"lineItem": {
"type": "object",
"properties": {
"sku": { "type": "string" },
"quantity": { "type": "integer", "minimum": 1 }
},
"required": ["sku", "quantity"],
"unevaluatedProperties": false
}
}
}
The document above is self-contained: the fragment pointers resolve inside the same resource, and $id gives the resource a stable identity. Keep the $id absolute and unique. A relative $id resolves against the retrieval URI, which means the same file can produce different base URIs depending on where it is hosted. Duplicate identifiers are worse: a registry that maps $id to schema will overwrite one of them, and validation results become load-order dependent.
Array contracts with prefixItems, items, and contains
Draft-07 expressed tuples with an array-valued items and used additionalItems for the tail. In 2020-12 the tuple form moved to prefixItems, which takes a non-empty array of schemas and validates each position independently. It does not constrain the array length. items is now a single schema that applies to elements after the prefix; when prefixItems is absent, it applies to every element.
That split removes a common ambiguity. prefixItems with two entries and items: false describes an exact two-element tuple. The same prefix with no items allows extra elements of any shape, while items: { "type": "string" } requires every extra element to be a string. Use minItems and maxItems for length rules; prefixItems only assigns schemas to positions.
contains is an assertion about matches rather than positions. By default at least one element must validate against its subschema. minContains raises the required count and maxContains caps it; both only have an effect when contains is present in the same schema object. minContains: 0 makes contains always pass, which is useful only when paired with maxContains to express an upper bound. The validator must test every element even after the first match, because contains produces an annotation listing matching indices, and unevaluatedItems consumes that annotation.
Object dependencies with dependentRequired, dependentSchemas, and propertyNames
Draft-07 used dependencies for two different jobs. A value that was an array required other properties; a value that was a schema applied a subschema to the whole object. 2020-12 splits the keyword along that fault line. dependentRequired takes an object whose values are arrays of property names. If the trigger property is present, every listed name must also be present. dependentSchemas takes an object whose values are schemas. If the trigger is present, the entire instance must validate against the corresponding schema.
The distinction matters because presence is not value. dependentRequired cannot say that a credit card number must match a pattern; it only says the field must exist. Use dependentSchemas when the dependent rule compares values, constrains a nested object, or needs if plus required logic. Keep the trigger check explicit: dependentSchemas does not require the trigger property to be valid, only present.
propertyNames applies a schema to every property name as a string. It is the right tool for naming rules such as length, character set, or a reserved prefix. It does not validate values, and it does not mark properties as evaluated for unevaluatedProperties; closing an object still requires properties, patternProperties, or additionalProperties to account for the values. A schema that relies on propertyNames alone and adds unevaluatedProperties: false rejects every property, because the names were never marked as evaluated β a common and confusing failure.
Conditional branches with if, then, and else
if evaluates a subschema but has no direct effect on the validation result. It selects whether then or else applies. Instances that pass if must also pass then when it is present; instances that fail if must pass else when it is present. If if is absent, both then and else are ignored entirely. An if without either branch is not an assertion; it only collects annotations, so it rarely belongs in a production schema unless another keyword consumes those annotations.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://api.example.com/schemas/payment.json",
"type": "object",
"properties": {
"method": { "enum": ["card", "invoice"] },
"cardNumber": { "type": "string" },
"billingEmail": { "type": "string", "format": "email" }
},
"required": ["method"],
"if": {
"properties": { "method": { "const": "card" } },
"required": ["method"]
},
"then": { "required": ["cardNumber"] },
"else": { "required": ["billingEmail"] }
}
The required inside if is not redundant with the root required. It ensures that a missing method takes the else path instead of passing if vacuously. That is the most common conditional bug: properties alone does not require the property it describes, so an absent discriminator makes the condition succeed for the wrong reason.
Conditionals are lexical, not global. An if inside one allOf branch cannot influence a then in a sibling branch. When several rules must compose, put each condition and its consequences in the same schema object, or use dependentSchemas to keep the trigger and its rule together.
Closing objects with unevaluatedProperties and unevaluatedItems
additionalProperties only sees properties and patternProperties in the same schema object. It cannot see declarations in a sibling allOf branch, a referenced schema, or a successful if branch. That is why the classic pattern fails: one branch closes the object, another branch declares a field, and the first branch rejects that field as additional. Repeating every field in every branch works but drifts; closing at the outer level with unevaluatedProperties is the durable fix.
unevaluatedProperties collects annotation results from properties, patternProperties, additionalProperties, and itself, including results produced by adjacent in-place applicators such as $ref, allOf, anyOf, oneOf, if/then/else, and dependentSchemas. It then applies its subschema only to properties that remain unevaluated. Failed evaluations do not contribute annotations, so a property declared only in a failing anyOf branch is still unevaluated and will be rejected by unevaluatedProperties: false.
unevaluatedItems follows the same model for arrays, consuming annotations from prefixItems, items, and contains. A subtle consequence is that contains marks only the indices that matched; if you also set unevaluatedItems: false, extra elements that do not match the contains schema are rejected. That combination is sometimes exactly what you want and sometimes a trap. propertyNames is not an annotation source for unevaluatedProperties; it validates names, not values.
These keywords depend on annotation collection, so implementation quality varies. Run the same fixtures across every validator in your stack, including the one inside your API gateway, and do not assume a compile-time schema check proves runtime behavior.
Annotations: contentEncoding, contentMediaType, and format
The content vocabulary is explicitly annotation-only. contentEncoding says how a string should be interpreted as encoded binary data, and contentMediaType names the media type of the decoded content. contentSchema can describe the decoded document. The specification forbids automatic decoding, parsing, or validation by default, and says a malformed string-encoded document must not invalidate the containing instance. Implementations may offer opt-in behavior, but it must return results separately.
format has a similar split. The Format-Annotation vocabulary collects format as an annotation. The Format-Assertion vocabulary turns it into an assertion, but support is optional, the standard meta-schema does not require it, and an implementation that asserts formats must provide options to disable that behavior by default. Even a validator that supports assertion may implement only a subset of formats, and its email check may be a pragmatic shape test rather than RFC 5322.
| Keyword | Vocabulary | Default behavior | Production response |
|---|---|---|---|
format | Format-Annotation | collected as an annotation; assertion disabled by default | validate with application code or explicitly enable assertion |
contentEncoding | Content | annotation only; no decoding by default | decode with a size limit and handle errors |
contentMediaType | Content | annotation only; no parsing by default | verify the media type before processing |
contentSchema | Content | annotation only; applied only by an opt-in consumer | validate the decoded document yourself |
title, description | Meta-data | documentation only | never use them for access control |
OpenAPI 3.1 inherits 2020-12 semantics for its Schema Object, but OpenAPI tooling is not a JSON Schema validator. A gateway may ignore unevaluatedProperties, treat format differently, or drop unknown keywords. Check the actual implementation rather than the specification badge, and never use format or contentEncoding as a security boundary. Validate emails with a library, limit decoded payload size, and parse untrusted documents in a sandbox.
Migrating from draft-07 without breaking clients
Migration starts with the $schema URI and continues through every changed keyword. The mechanical replacements are short, but each one can alter results:
definitionsbecomes$defs. A JSON Pointer such as#/definitions/addressstill resolves if that location exists, but standardize on$defsso tools and reviewers share one convention.- Array-valued
itemsbecomesprefixItems, andadditionalItemsbecomes the single-schemaitems. A draft-07 tuple that relied onadditionalItems: falseshould becomeprefixItemsplusitems: false. dependenciessplits intodependentRequiredfor arrays anddependentSchemasfor schemas. A schema-valued dependency keeps its whole-object semantics independentSchemas.$refsiblings now apply. Remove constraints that were previously ignored, and movedescriptionordefaultnext to$refonly when you intend the annotation to travel with the reference site.$idloses non-empty fragments; use$anchorfor plain-name fragments. Make every$idabsolute and unique.$recursiveRefand$recursiveAnchorgive way to$dynamicRefand$dynamicAnchorfor recursive extension. Most schemas do not need them, but libraries that expose them do.containsgainsminContainsandmaxContains, andunevaluatedPropertiesplusunevaluatedItemsbecome available.
Do not migrate by search and replace. Validate the converted schema against the 2020-12 meta-schema, then replay a fixture corpus that covers every accepted and rejected case from the old schema. Treat each difference as a deliberate contract change. If the consumer is OpenAPI 3.1, also test the OAS base dialect: OAS-specific keywords such as discriminator are ignored by plain JSON Schema validators, and some OAS tools still lag on 2020-12 applicators.
Verification checklist for production schemas
Verify the schema and the validator, not only a happy-path instance. A schema can be valid JSON and still be semantically wrong; a validator can accept a schema and silently ignore a keyword it does not implement.
| Check | How to test | Pass criteria |
|---|---|---|
| Dialect declaration | Inspect the root $schema and the validator's reported dialect | Exact 2020-12 URI; no draft-07 URI remains |
| Resource identity | List every $id in the bundle | All absolute, unique, and free of non-empty fragments |
| Reference resolution | Resolve every $ref with the network disabled | Every reference resolves from the bundle; no fetch occurs |
| Tuple boundary | Validate 0, N, and N+1 items against a prefixItems schema | Prefix positions and tail rules behave as specified |
| Contains counts | Validate 0, minContains, maxContains, and maxContains + 1 matches | Counts pass and fail at the intended boundaries |
| Dependent fields | Toggle the trigger property and its dependents | dependentRequired and dependentSchemas activate only on presence |
| Conditional branches | Validate one card, one invoice, and neither | Exactly the intended then or else branch applies |
Closure across allOf | Declare fields in separate branches, then add an unknown field | unevaluatedProperties: false accepts declared keys and rejects the unknown one |
| Annotation safety | Submit a malformed email and malformed Base64 | The schema may accept; the application rejects with a clear error |
| Migration parity | Replay the draft-07 fixture corpus after conversion | Only intentional differences appear |
The JSON Schema validator is useful for inspecting draft-07 documents and self-contained schemas in the browser. It runs Ajv's draft-07 build and does not fetch remote $ref, so prove 2020-12-only behavior such as prefixItems, unevaluatedProperties, and dependentSchemas with a validator configured for the 2020-12 dialect. The JSON to JSON Schema generator produces a 2020-12 starting point from a real sample, but a sample cannot reveal optional fields, enumerations, or closure rules; review and tighten the output. Use the JSON formatter to inspect the raw payload before validation, especially when a number, duplicate key, or Unicode escape may have changed before the validator saw it.
A schema is a contract with a dialect, a resolver, and a validator attached. Pin all three, test the boundaries, and treat annotations as documentation rather than enforcement. That discipline is what makes 2020-12's precision worth its complexity.
Frequently asked questions
Do I need to migrate an existing draft-07 schema to 2020-12?
Not automatically. Migrate when you need unevaluatedProperties, prefixItems, dependentRequired, or a toolchain that already supports 2020-12. A working draft-07 schema should stay pinned to draft-07 until every consumer, including OpenAPI tooling and client generators, can handle the newer dialect.
Why does unevaluatedProperties: false still reject a property declared in allOf?
Because annotations from a failing branch are dropped. If the allOf branch that declares the property also fails another assertion, that property remains unevaluated. Fix the failing branch or move the declaration to a schema that always applies; unevaluatedProperties cannot see declarations from unsuccessful evaluations.
Can I put description or default next to $ref in 2020-12?
Yes. In 2020-12 $ref is an ordinary applicator, so sibling keywords are evaluated. That differs from draft-07, where everything next to $ref was ignored. Keep semantic constraints inside the referenced schema and use siblings only for annotations or deliberately combined constraints.
Does contentEncoding validate that a string is valid Base64?
No. contentEncoding and contentMediaType are annotations in the content vocabulary. The specification forbids decoding or validating the string by default. Decode the value in application code, enforce a size limit, and treat a malformed payload as an application error rather than a schema failure.
How do I require at least two matching items in an array?
Use contains with the item schema and set minContains to 2. contains alone means at least one match; minContains raises the floor, maxContains caps it, and minContains: 0 turns contains into an upper-bound check used with maxContains. Every item is still tested so annotations stay complete.
JsonMind guides are written and reviewed by the engineering team. We check each guide against the relevant RFC or vendor documentation, link the primary sources, and update the guide when behavior changes.
Primary sources are linked at the end of each guide.