Updated
A first example
This JSON describes a user.
{
"id": 42,
"name": "Ada Keller",
"email": "ada@example.com",
"roles": ["admin"]
}The schema for it
The schema says the document is an object, names each property and its type, and lists which properties must be present.
{
"type": "object",
"properties": {
"id": { "type": "integer", "minimum": 1 },
"name": { "type": "string", "minLength": 1 },
"email": { "type": "string", "format": "email" },
"roles": {
"type": "array",
"items": { "enum": ["admin", "editor", "viewer"] }
}
},
"required": ["id", "name", "email"],
"additionalProperties": false
}The keywords you will use most
- type: string, number, integer, boolean, object, array or null.
- properties: the fields of an object, each with its own schema.
- required: the fields that must be present. Fields not listed are optional.
- additionalProperties: set it to false to reject fields the schema does not name.
- items: the schema every element of an array must match.
- enum: a fixed list of allowed values.
- minimum, maximum, minLength, maxLength, minItems, maxItems: limits on numbers, strings and arrays.
- format: a hint such as email, date-time, uri or uuid.
- description: a sentence for the people, and the language models, that read the schema.
- $ref: a pointer to a schema defined once under $defs and reused.
Where JSON Schema is used
- API validation. The server rejects a request body that does not fit, before any other code runs.
- API documentation. OpenAPI describes request and response bodies with JSON Schema.
- Config files. Editors such as VS Code read a schema to autocomplete and underline mistakes in files like package.json.
- LLM structured outputs. You give the model a schema and the provider guarantees the answer fits it.
- Test data. A generator can fill a schema with random values.
Which draft to use
JSON Schema has versions called drafts. Draft-07 has the widest support in validators and tools. Draft 2020-12 is the newest and is what OpenAPI 3.1 uses.
For most schemas the two look the same. The differences are in less common keywords, such as $defs replacing definitions. Pick the draft your validator supports and name it in the $schema field.
How to validate
Use a library. Ajv is the common choice in JavaScript, and jsonschema in Python. Both take a schema and a document and return a list of errors with the path of each failing field.