Full name: JavaScript Object Notation (JSON) Schema.
Definition
JSON Schema is a language for describing which JSON §12.26 documents a program accepts. JSON (JavaScript Object Notation) is a text format for data built from objects (sets of named values), arrays §14.5, strings, numbers, true, false and null. A schema is itself a JSON document listing constraints, such as required names, types and ranges. A validator program checks one document, the instance, against the schema and reports each violated constraint. The specification (json-schema.org) has dated versions, each defining a dialect, a set of keywords; this entry uses 2020-12 [504].
The idea
A device receives a settings record as JSON text, {"version": 5, "kind": "full"}. Before the program acts on the record, it must check many plain facts: version is present and is a whole number, kind is one of two allowed words, and no unknown names appear. Written by hand, such checks are long, easy to get wrong and different in every program that reads the record. A schema states them once, as data. Any validator, in any programming language, then applies the same rules, and the schema also documents the record format for people.
A paper form and a clerk are a fair picture. The form marks the required boxes and what may go in each, and the clerk rejects a form with an empty required box or a word in a number box. The clerk looks only at the form in hand and cannot see whether the same form number was used last week, whether the account named on it exists, or whether the person handing it in may make the request. A validator has exactly this limit: it judges one instance against the schema alone. The picture stops in one respect: a clerk can phone someone and ask, while a validator has no source of information except the instance and the schemas.
How it works
A schema is a JSON object whose member names are keywords. Each keyword states one constraint, and an instance is valid only if it satisfies every keyword. The common keywords of the 2020-12 dialect are these.
type: the kind of value, one of"object","array","string","number","integer","boolean"and"null"."integer"accepts any number with no fractional part, so5.0passes and5.5fails.properties: a map from a member name to a schema that the member’s value must satisfy if the member is present.required: a list of member names that must be present.additionalProperties: a schema for every member that is not named byproperties, or matched bypatternProperties(which matches names by a regular expression §12.44), in the same schema object. The valuefalseforbids such members.minimum,maximum,exclusiveMinimum,exclusiveMaximum: bounds on a number.minLength,maxLength: bounds on the length of a string, counted in Unicode §12.48 characters.pattern: a regular expression that must match somewhere in the string; it is not anchored, so it needs^at the start and$at the end to constrain the whole string.enum: a list of allowed values.const: the one allowed value.items,prefixItems,minItems,maxItems,uniqueItems: constraints on arrays.uniqueItemsrejects an array in which two items are equal as whole values.dependentRequired: when one named member is present, other named members must be present too.
A subschema is a schema nested inside another schema. Four keywords combine subschemas: allOf (the instance must satisfy every listed subschema), anyOf (at least one), oneOf (exactly one) and not (the instance must fail the subschema). The keywords if, then and else state a condition. When the instance satisfies the if subschema, it must also satisfy the then subschema; otherwise it must satisfy the else subschema. The outcome of if never makes the instance invalid by itself. An if/then pair therefore says “when this holds, that must hold too”, for example “when kind is "patch", the member base is required”.
Schemas refer to each other. $id gives a schema a URI (uniform resource identifier), a name written like a web address, so that other schemas can point to it. $defs holds named subschemas for reuse. $ref applies the schema found at a URI, as if it were written in place. The part of that URI after the # sign is usually a JSON Pointer, a path into a JSON document defined in RFC 6901 [505]: member names and array positions separated by /. #/$defs/version therefore means the member version inside the member $defs of the current schema. Inside a JSON Pointer, ~1 stands for a / that is part of a name and ~0 for a ~. Finally, $schema names the dialect the schema is written in, for 2020-12 the URI https://json-schema.org/draft/2020-12/schema. A validator looks a $ref up in its own registry of known schemas; whether it may also download an unknown URI depends on the implementation, so a careful program registers every schema it needs in advance.
Closing a record needs care when the schema is assembled from parts. additionalProperties sees only the properties and patternProperties written next to it in the same schema object. It does not see members named in subschemas reached through allOf, $ref or if/then, and it treats those members as additional. unevaluatedProperties, introduced in the 2019-09 dialect [506], looks through such subschemas. It applies to every member that no keyword has evaluated, counting the keywords of its own schema object and of every subschema that the instance satisfied through allOf, anyOf, oneOf, $ref, if, then or else. Members named only in a subschema that the instance failed do not count as evaluated. "unevaluatedProperties": false therefore closes a record built from several subschemas: a member is allowed when some applied part of the schema names it, and rejected otherwise.
Validation runs in this order.
A JSON parser turns the text into values. The validator works on these parsed values, not on the original bytes.
The program selects the schema, its dialect and every schema that it refers to.
The validator walks the instance and the schema together and applies each keyword to the part of the instance that the keyword governs.
The validator reports either “valid” or a list of errors. Each error names the keyword that failed and the place in the instance, written as a JSON Pointer such as
/version.The program rejects an invalid instance before acting on it. It then performs the checks that need information from outside the instance.
Worked example
The schema below describes the settings record from above. It requires version and kind, requires base when kind is "patch", and rejects any other member.
{"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["version", "kind"],
"properties": {
"version": {"type": "integer", "minimum": 0},
"kind": {"enum": ["full", "patch"]},
"base": {"type": "integer", "minimum": 0}},
"if": {"properties": {"kind": {"const": "patch"}}},
"then": {"required": ["base"]},
"unevaluatedProperties": false}
Six instances and the verdicts of a 2020-12 validator:
{"version": 5, "kind": "full"}is valid. Both required members are present, 5 is an integer and , and"full"is in the list. Theifsubschema fails becausekindis not"patch", and the schema has noelse, so nothing more is required.{"version": 5, "kind": "patch"}is invalid. Theifsubschema holds, sothenapplies, andthenrequiresbase, which is missing.{"version": 5, "kind": "patch", "base": 3}is valid.{"version": 5, "kind": "full", "note": "x"}is invalid. No keyword namesnote, so"unevaluatedProperties": falserejects it.{"version": -1, "kind": "full"}is invalid at/version, because .{"version": 5.5, "kind": "full"}is invalid at/version, because 5.5 has a fractional part.
Now the device has already installed version 7. It keeps the number 7 in protected storage as its version high-water mark §8.27 and must refuse any record whose version is not greater than 7, so that nobody can reinstall an old record with a known flaw. Instance 1 carries version 5 and passes the schema. The schema cannot refuse it: the number 7 is neither in the instance nor in the schema. The program must read 7 from its stored state and compare. Because is false, the program refuses the record. Generating a fresh schema with "exclusiveMinimum": 7 for this one check would only copy the stored number into the schema; the number still comes from the device’s state, and the schema would have to be regenerated after every update.
A second example shows why the schema above closes the record with unevaluatedProperties and not with additionalProperties. A base schema is {"properties": {"version": {"type": "integer"}}, "required": ["version"]}. A record schema is {"allOf": [B], "properties": {"kind": {"type": "string"}}, "additionalProperties": false}, where B stands for the base schema, written out or referenced with $ref. The instance {"version": 5, "kind": "full"} fails : additionalProperties sees only kind in the properties of , so it counts version as additional and forbids it. With "unevaluatedProperties": false in place of "additionalProperties": false, the same instance passes, because , applied through allOf and satisfied, evaluated version. The instance {"version": 5, "kind": "x", "z": 1} still fails, because no part of the schema names z.
Stated precisely
Write for a validator’s verdict on an instance under a schema . In the 2020-12 dialect the verdict depends only on , on and on the schemas that refers to. Nothing else enters: not other records, not stored state, not the current time, not the identity of the sender, and not the bytes from which was parsed. An assertion is a keyword that can make an instance invalid; an annotation is a keyword that only attaches information. The guarantee reads: if is true, then satisfies every assertion of as the dialect defines it. The guarantee rests on four assumptions.
The validator implements the dialect correctly.
is the intended schema, and every reference resolves to the intended schema.
The validator applies the dialect that was written for.
Every keyword the program relies on is an assertion, not an annotation. By default
formatis an annotation.
A consequence follows directly. Let be a rule about the instance and some context , such as the stored high-water mark or the current time. Suppose two contexts and exist such that is true and is false for the same . Then no single schema decides , because has the same value in both contexts.
Inside one instance, a schema can require members, restrict each value on its own, require members when another member is present (dependentRequired), and make requirements depend on a value equaling a constant (if with const). Apart from uniqueItems, which compares whole array items for equality, the 2020-12 dialect has no keyword that compares one value of the instance with another. It cannot say that start is at most end, that a declared length equals the length of an encoded payload, or that a checksum §4.32 matches the content. The keywords contentEncoding and contentMediaType describe an encoded payload, but in 2020-12 they are annotations and check nothing.
Limits and common mistakes
Validation is neither authentication §1.6 nor authorization §1.7. A record that passes says nothing about who wrote it or whether its author may make the request. A digital signature §5.14 or a message authentication code §5.7 over the record, and an authorization check, are separate steps.
Unknown keywords are ignored. A misspelled "requred" constrains nothing. A 2020-12 schema run by a validator for the older draft-07 dialect [507] silently loses unevaluatedProperties and prefixItems, which draft-07 does not define, and accepts what the author meant to reject. Declare the dialect with $schema and use a validator for that dialect.
Records are open by default. Unless additionalProperties or unevaluatedProperties is set to false, any extra member passes. properties alone does not make a member required; only required does.
An if subschema holds when the member it tests is absent. {"properties": {"kind": {"const": "patch"}}} is satisfied by an instance with no kind at all, so the then branch applies to it. Make the tested member required, inside if or in the enclosing schema.
By default format checks nothing. In 2020-12 it is an annotation, and a validator checks it only when told to. Even then a validator may skip a format it cannot check: the Python §12.23 jsonschema library, for example, checks "date-time" only when an optional helper package is installed. A checked format concerns spelling only; a well-formed timestamp can still lie in the past.
The validator sees parsed values. The parser has already decided what to do with a member name that appears twice (many parsers keep the last value) and with a number too large for its number type, and the schema cannot detect either. The duplicate JSON key entry treats the first problem. Nor does validation bound the cost of parsing: a very large or deeply nested document consumes memory in the parser before the validator runs, so limit the input size first.
A pass is a statement about one schema. Record which schema accepted the instance, by its $id and a hash of its content, and make sure the program that acts on the record uses the same parsed value that was validated. The jsonschema and referencing §15.33 entry describes one Python implementation of these steps.
Questions answered
Which invariants require cross-record or temporal checks beyond one schema?
Every invariant whose truth depends on anything other than the one instance being validated needs a check outside the schema, because a JSON Schema validator sees only that instance and the schemas. JSON Schema is a language of constraints on one JSON (JavaScript Object Notation) document, the instance. The invariants that need more are these.
Uniqueness across records: no two records share an identifier. Even inside one array,
uniqueItemsrejects only items that are equal as whole values, so two items with the sameidand different other members pass.References to other records: a member names another record, key or file that must exist.
Order over time: a version number must exceed the last one accepted (a version high-water mark), a sequence number must never have been used before (protection against a replay attack §1.26), a counter must only increase.
Validity in time: a not-before time or an expiry time compared with the current time.
Allowed state transitions: a request is legal only from the receiver’s current state.
Authenticity and authorization: who produced the record, and whether that party may ask for this.
Aggregates: a limit on a total over many records, such as a quota.
One more group lies inside a single record yet outside the schema language: relations that compare two values, such as start being at most end, a declared length equaling the length of a decoded payload, or a checksum matching the content. Check all of these in program code after schema validation, against trusted state read at the moment of the decision, and record the new state in the same step that accepts the record, so that two records cannot both pass against the same old state.
Related entries: JSON (§12.26), jsonschema and referencing (§15.33), Version high-water mark (§8.27), Authentication coverage (§5.41), Duplicate JSON key (§15.20), Regular expression (§12.44). Further reading: [53, 504, 505, 506, 507].