FormatterHQ

Data formats

JSON Schema Explained: How to Write and Validate a Schema

What JSON Schema is, how to write one from scratch (types, properties, required, enums, nested objects and arrays), and how to validate your data against it.

Published 5 min read

JSON Schema lets you describe what a valid JSON document looks like — and then check real data against that description automatically. It is how APIs document their request and response shapes, how config files catch typos before they ship, and how you stop bad data entering a system. This guide explains what a schema is, how to write one field by field, and how to validate your JSON against it.

If JSON itself is still new to you, start with what JSON is, then come back here.

What JSON Schema is

A JSON Schema is a JSON document that describes the structure of other JSON documents. A validator reads the schema and your data and reports every rule the data breaks — a missing required field, a string where a number was expected, or a value outside an allowed set. Unlike a plain syntax check, which only confirms the brackets and quotes are valid, a schema checks meaning: that price is a non-negative number and status is one of a fixed list.

A first schema

Say you expect objects like {"id": 1, "name": "Ada", "email": "ada@example.com"}. A schema for that looks like this:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "id":    { "type": "integer" },
    "name":  { "type": "string", "minLength": 1 },
    "email": { "type": "string", "format": "email" }
  },
  "required": ["id", "name"],
  "additionalProperties": false
}

Read it top to bottom: the document must be an object; it may have id, name and email with those types; id and name must be present; and additionalProperties: false forbids any field you did not list. Paste this schema and a sample into the JSON Schema validator to watch it accept good data and reject bad.

The keywords you will use most

  • type — string, number, integer, boolean, object, array or null.
  • properties — the allowed keys of an object and a schema for each.
  • required — an array of property names that must be present.
  • enum — a fixed list of allowed values, e.g. "status": {"enum": ["open", "closed"]}.
  • minimum/maximum, minLength/maxLength, pattern — value constraints for numbers and strings.
  • format — named formats such as email, date-time, uri and uuid.

Nested objects and arrays

Schemas compose: a property can itself be an object with its own properties, and an array uses items to describe each element:

{
  "type": "object",
  "properties": {
    "user": {
      "type": "object",
      "properties": { "id": { "type": "integer" } },
      "required": ["id"]
    },
    "tags": {
      "type": "array",
      "items": { "type": "string" },
      "minItems": 1,
      "uniqueItems": true
    }
  }
}

Here tags must be an array of strings, with at least one entry and no duplicates. This nesting is how a schema mirrors a real payload, no matter how deep it goes.

Validating in code

Every ecosystem has a validator library. In JavaScript, Ajv is the standard:

import Ajv from "ajv";
const ajv = new Ajv({ allErrors: true });
const validate = ajv.compile(schema);

if (!validate(data)) {
  console.log(validate.errors); // every rule that failed, with paths
}

In Python, the jsonschema package does the same. Wire validation into your API boundary so malformed requests are rejected with a clear message instead of corrupting data downstream.

Generate a schema, then tighten it

Writing a schema from scratch for a large payload is tedious. Start with the JSON to JSON Schema tool — paste a representative sample and it infers types and properties. Then do the important work by hand: mark the truly required fields, replace loose string types with enum or format where values are constrained, and set additionalProperties: false if the shape is closed. To exercise the finished schema, generate conforming sample data or edge cases to test with the random JSON generator.

Where schemas pay off

  • API contracts — validate requests and responses so clients and servers agree on the shape.
  • Config safety — editors like VS Code use a referenced schema to autocomplete and flag errors as you type.
  • Code generation — a schema is the robust source for generating typed models (the schema-first alternative to inferring types from one sample).

Using a schema in your editor

One of the quietest wins is editor support. When a JSON file references a schema — either through a $schema URL or a project-level mapping in VS Code’s settings — the editor autocompletes allowed keys, shows the description of each field on hover, and underlines anything that breaks a rule as you type. This turns a schema from a server-side gate into a live authoring aid for config files like package.json or your own app settings, catching mistakes before the file is ever saved or committed. Publishing a schema for your own config format is a small effort that pays back every time someone edits the file.

Reusing parts of a schema with $ref

Once a schema grows, you repeat the same sub-shapes — an address, a money amount, a timestamp. Define them once under $defs and point to them with $ref so there is a single source of truth:

{
  "type": "object",
  "properties": {
    "billing":  { "$ref": "#/$defs/address" },
    "shipping": { "$ref": "#/$defs/address" }
  },
  "$defs": {
    "address": {
      "type": "object",
      "properties": { "city": { "type": "string" }, "zip": { "type": "string" } },
      "required": ["city"]
    }
  }
}

Now both billing and shipping are validated by the same address definition, and a change in one place applies everywhere. References can also point at external schema files by URL, which is how large API specifications stay maintainable.

Mistakes that make a schema too loose

A schema is only as strict as you make it. Three oversights let bad data through:

  • Forgetting required. Without it, every field is optional — an empty object {} passes. List the fields your code actually depends on.
  • Leaving additionalProperties open. By default, extra undeclared fields are allowed. Set it to false when the shape is closed, so a misspelled emial is caught instead of silently ignored.
  • Using bare string everywhere. If a value is really one of a few options or a specific format, say so with enum, pattern or format — that is where a schema earns its keep.

Validate representative good and bad samples in the schema validator to confirm the schema accepts what it should and rejects what it should not.

Key takeaways

  • JSON Schema describes structure and content, not just syntax.
  • Core keywords: type, properties, required, enum, items, plus value constraints.
  • Generate a draft schema from a sample, then tighten required fields and allowed values by hand.
  • Validate at your API boundary with Ajv (JS) or jsonschema (Python), or online in the schema validator.
  • JSON
  • JSON Schema
  • Validation
  • APIs

Frequently asked questions

What is JSON Schema?
JSON Schema is a vocabulary — itself written in JSON — that describes the shape of a JSON document: which fields exist, their types, which are required, and what values are allowed. A validator checks a document against the schema and reports every rule it breaks.
How do I validate JSON against a schema?
Paste your schema and your data into the JSON Schema validator. It lists each failing rule with the path to the offending field. In code, use a library such as Ajv (JavaScript) or jsonschema (Python).
What is the difference between JSON Schema validation and plain JSON validation?
Plain validation only checks that the syntax is well-formed. JSON Schema validation also checks the structure and content — that age is a number, email is present, and status is one of your allowed values.
Can I generate a JSON Schema from an example?
Yes — the JSON to JSON Schema tool infers a starting schema from a sample payload. Treat the result as a draft: tighten the types, mark required fields and add enum constraints by hand.
Which JSON Schema draft should I use?
For new projects use the latest widely-supported draft (2020-12). Declare it with the $schema keyword so validators apply the right rules. Many tools also still support draft-07, which is common in existing codebases.

Tools used in this guide