JSON tells you nothing about what a document should contain. Is age required? Can email be null? Is "plan": "gold" allowed, or only “free” and “pro”? JSON Schema is the standard way to write those rules down in JSON itself, so that programs can check data automatically and people can read the contract. This guide explains how a schema is put together, the keywords you will use most, and how to generate a first draft from sample data instead of writing it from scratch.

What a schema is for

A JSON Schema is a JSON document that describes the shape of other JSON documents. The same schema can serve several jobs:

  • Validation — reject an API request, a config file or an import that is missing fields or has the wrong types, with a clear error instead of a crash later.
  • Documentation — OpenAPI (Swagger) uses JSON Schema to describe request and response bodies, and many API docs are generated from it.
  • Editor support — VS Code and other editors use schemas to autocomplete and underline mistakes in files such as package.json or tsconfig.json.
  • Code generation and forms — tools can generate types or build input forms from a schema.
  • Structured output from AI models — several LLM APIs accept a JSON Schema to constrain the shape of the model’s reply.

A first schema

Here is a user record and a schema that describes it:

{ "id": 1, "email": "asha@example.com", "plan": "pro", "tags": ["vip"] }
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "User",
  "type": "object",
  "properties": {
    "id":    { "type": "integer", "minimum": 1 },
    "email": { "type": "string", "format": "email" },
    "plan":  { "enum": ["free", "pro"] },
    "tags":  { "type": "array", "items": { "type": "string" }, "uniqueItems": true }
  },
  "required": ["id", "email", "plan"],
  "additionalProperties": false
}

Read it top to bottom: the document must be an object; id must be a whole number of at least 1; plan must be one of two values; tags, if present, must be a list of distinct strings; three fields are required; and no other fields are allowed. $schema says which version of the specification the schema follows — 2020-12 is the current one.

The keywords you will use most

KeywordApplies toMeaning
typeAnystring, number, integer, boolean, object, array or null — or a list such as ["string", "null"]
enum, constAnyValue must be one of a list, or exactly one value
propertiesObjectsA schema for each named field
requiredObjectsFields that must be present
additionalPropertiesObjectsfalse rejects fields not listed in properties
itemsArraysA schema every element must match
minItems, maxItems, uniqueItemsArraysLength and duplicate rules
minLength, maxLength, patternStringsLength limits and a regular expression the value must match
formatStringsA named format such as date-time, date, email, uri or uuid
minimum, maximum, exclusiveMinimum, multipleOfNumbersRange and step rules
description, default, examplesAnyDocumentation only; they do not affect validation

Required, optional and nullable are three different things

This trips up almost everyone, because many languages blur the distinction:

  • Required means the key must be present. It is listed in required.
  • Optional means the key may be missing. It is in properties but not in required.
  • Nullable means the key may be present with the value null: "type": ["string", "null"].

A field can be required and nullable (“always send phone, even if it is null”) or optional and not nullable (“leave referrer out rather than sending null”). Decide which you mean for each field; the difference matters to whoever consumes the data.

Reusing definitions with $defs and $ref

When the same shape appears in several places — an address for billing and shipping, say — define it once under $defs and point to it with $ref:

{
  "type": "object",
  "properties": {
    "billing":  { "$ref": "#/$defs/address" },
    "shipping": { "$ref": "#/$defs/address" }
  },
  "$defs": {
    "address": {
      "type": "object",
      "properties": {
        "city":    { "type": "string" },
        "pincode": { "type": "string", "pattern": "^[1-9][0-9]{5}$" }
      },
      "required": ["city", "pincode"]
    }
  }
}

The pattern above accepts six-digit Indian PIN codes. Note that PIN codes, phone numbers and IDs with leading zeros are best stored as strings, not numbers.

Either-or shapes: anyOf, oneOf and allOf

Some data comes in more than one valid shape. anyOf passes if the value matches at least one of the listed schemas, oneOf if it matches exactly one, and allOf if it matches all of them (a way to combine rules). A payment might be either a card or a UPI ID:

"payment": {
  "oneOf": [
    { "type": "object", "properties": { "method": { "const": "card" }, "last4": { "type": "string" } }, "required": ["method", "last4"] },
    { "type": "object", "properties": { "method": { "const": "upi" },  "vpa":   { "type": "string" } }, "required": ["method", "vpa"] }
  ]
}

A const “tag” field like method makes either-or shapes much easier to validate and to read in error messages. Prefer anyOf unless overlapping matches really must be rejected; oneOf has to test every branch and gives more confusing errors.

Generate a draft from sample data

Writing a schema by hand for a large API response is slow. A faster route is to generate a draft from real examples with JSON to JSON Schema and then tighten it. Given an array of two user records — one with a referrer field and a null phone, one without — it produces:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "User",
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "id":       { "type": "integer" },
      "email":    { "type": "string" },
      "plan":     { "type": "string" },
      "signedUp": { "type": "string", "format": "date-time" },
      "tags":     { "type": "array", "items": { "type": "string" } },
      "phone":    { "type": ["string", "null"] },
      "referrer": { "type": "string" }
    },
    "required": ["id", "email", "plan", "signedUp", "tags", "phone"]
  }
}

The generator compares every record, so a field missing from any record becomes optional and a field that is sometimes null becomes nullable. It also recognises ISO dates and times, UUIDs and URLs. What it cannot know are your business rules, so review the draft:

  • Turn free-text fields with a fixed set of values into enum (“plan” above).
  • Add format, pattern, minimum and length limits where they matter.
  • Check every optional field: was it really optional, or just missing from your sample? More varied samples give better drafts.
  • Decide whether to reject unknown fields with additionalProperties: false — the generator’s strict option adds it everywhere. It catches typos, but makes it harder to add fields later without breaking older clients.
  • Add description to anything that is not obvious from its name.

Validating data against a schema

Validation runs in your code or pipeline using a library — for example Ajv in JavaScript, jsonschema in Python or networknt/json-schema-validator in Java. Two behaviours surprise people:

  • format is not enforced by default. In the 2020-12 specification, format is an annotation unless the validator is configured to check it. Turn on format validation (in Ajv, by adding the ajv-formats plugin) if you rely on it, or use pattern.
  • Unknown keywords are ignored. A typo such as "requried" is not an error — the rule is simply not applied. Test your schema against a few deliberately bad documents to make sure it rejects them.

Before you validate, make sure the document is valid JSON at all: the JSON Validator pinpoints syntax errors by line and column, and JSON Repair fixes common problems such as trailing commas and single quotes.

JSON Schema, TypeScript or Zod?

They overlap but serve different purposes. TypeScript types exist only at compile time and vanish when your code runs, so they cannot check data arriving from outside. JSON Schema is language-neutral and travels with the data — ideal for APIs, configs shared between services, and documentation. Zod and similar libraries validate at run time inside a TypeScript codebase and give you the static type for free. Many teams use a schema at the boundary and generated types inside. You can generate all three from the same sample with JSON to JSON Schema, JSON to TypeScript and JSON to Zod; our guide to generating types from JSON compares the outputs in more languages.