What is JSON Schema? Examples you can copy

JSON Schema is a way to describe what a JSON file must look like. The schema itself is written in JSON. A validator reads the schema and your data. Then it tells you if the data fits.

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 data is an object. It names each property and its type. It also lists which properties must be there.

{
  "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 one has its own schema.
  • required: the fields that must be there. Fields not listed are optional.
  • additionalProperties: set it to false to reject fields the schema does not name.
  • items: the schema that every item in 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 AI models, that read the schema.
  • $ref: a pointer to a schema you define once under $defs and then reuse.

Where JSON Schema is used

  • API validation. The server turns away a request body that does not fit. This happens before any other code runs.
  • API docs. OpenAPI describes request and response bodies with JSON Schema.
  • Config files. Editors like VS Code read a schema to suggest values and underline mistakes. This works in files like package.json.
  • LLM structured outputs. You give the model a schema, and the provider makes sure 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 works with the most validators and tools. Draft 2020-12 is the newest. It is the one OpenAPI 3.1 uses.

For most schemas the two look the same. The changes are in less common keywords. For example, $defs replaces definitions. Pick the draft your validator supports, and name it in the $schema field.

How to validate

Use a library. Ajv is the common pick in JavaScript, and jsonschema in Python. Both take a schema and your data. They return a list of errors, with the path of each field that failed.

Tools for this guide

All tools →

More guides

All guides →