Skip to content
Velloreth
Technology 5 min read

JSON Schema: Validating JSON With a Schema

A JSON Schema describes the shape of a JSON document. Learn the types, the constraints, the composition, and the validation.

By

The idea

A JSON Schema describes the shape of a JSON document.

A validator checks a document against it.

It is written in JSON, which makes it portable.

The basic schema

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

type is the JSON type.

properties lists the allowed keys.

required lists the keys that must be present.

additionalProperties: false rejects an unknown key.

The types

TypeNotes
stringwith minLength, maxLength, pattern, format
numberwith minimum, maximum, multipleOf
integera number with no fraction
booleantrue or false
objectwith properties, required
arraywith items, minItems, uniqueItems
nullthe null value

A type can be a list.

{ "type": ["string", "null"] }

The constraints

{
  "type": "string",
  "minLength": 3,
  "maxLength": 100,
  "pattern": "^[a-z0-9-]+$"
}
{
  "type": "array",
  "items": { "type": "string" },
  "minItems": 1,
  "uniqueItems": true
}

format is an annotation, and a validator may or may not enforce it.

FormatMeaning
emailan email address
uria URI
date-timean ISO 8601 timestamp
uuida UUID
ipv4an IPv4 address

The composition

KeywordMeaning
allOfevery subschema must match
anyOfat least one must match
oneOfexactly one must match
notmust not match
{
  "oneOf": [
    { "type": "object", "required": ["cardNumber"] },
    { "type": "object", "required": ["iban"] }
  ]
}

oneOf is the strictest, because a document that matches two subschemas fails.

The reference

{
  "properties": {
    "author": { "$ref": "#/$defs/User" }
  },
  "$defs": {
    "User": {
      "type": "object",
      "properties": { "id": { "type": "string" } },
      "required": ["id"]
    }
  }
}

$ref avoids a duplication.

A local reference uses a JSON Pointer.

A remote reference uses a URL, which requires a fetch.

The validation

import Ajv from 'ajv';

const ajv = new Ajv();
const validate = ajv.compile(schema);

if (!validate(data)) {
  console.error(validate.errors);
}

Ajv is the common JavaScript validator.

A validator reports the errors with a path and a message.

A strict mode rejects an unknown keyword, which catches a typo.

The code generation

A tool generates a type from the schema.

// generated from the schema
interface User {
  id: string;
  name: string;
  email?: string;
}

The schema is the source of truth, and the type is derived.

That keeps the validation and the type in sync, which is the main benefit.

The use cases

UseBenefit
An API payloada contract
A config filea caught typo
A forma generated UI
A messagea validated event
A test fixturea known shape

An OpenAPI document uses a JSON Schema for the request and the response.

The schema in an API

A schema is most valuable at the boundary of a service, because that is where a misunderstanding becomes a bug. The request body is validated against a schema before the handler runs, so the handler can assume the shape and the types, and an invalid request is rejected with a clear error rather than failing deep in the code. The response is validated in a test, so a change to the handler that breaks the contract is caught before it ships. The schema is also the source of the documentation, because a tool generates the API reference from it, and the source of the client, because a tool generates a typed client. The discipline that makes it work is that the schema is the source of truth and the code is derived from it, because a schema that is written after the code drifts from it within a release or two.

The versioning

A schema is a contract, and a contract that changes without a version breaks a consumer. The safe changes are to add an optional property, to widen a constraint, and to add a new value to an enum that the consumer treats as unknown. The breaking changes are to add a required property, to remove a property, to narrow a constraint, and to change a type. A version in the URL or in a header is the common way to signal a break, and a deprecation period gives the consumer time to migrate. A schema that is validated in the pipeline catches the accidental break, because a change that removes a required property fails the test that validates the old fixture.

Common mistakes

No additionalProperties: false. A typo is accepted.

A format assumed to be enforced. It may be an annotation.

A oneOf that matches two. A surprising failure.

No $schema. The draft is ambiguous.

A $ref to a remote URL. A fetch at validation time.

A schema that is not versioned. A breaking change.

A validation on the client only. A security hole.

A large schema in one file. Hard to maintain.

No error message. The user does not know what is wrong.

A schema that is out of sync with the code. A false confidence.

A quotable summary

A JSON Schema describes the shape of a JSON document, and a validator checks a document against it and reports the errors. The core keywords are type, properties, required and items, composition uses allOf, anyOf, oneOf and not, and additionalProperties: false rejects an unknown key. A schema is a contract, so it should be versioned, and a tool can generate a type or a form from it.

For the related topics, see form-validation-patterns and rest-api-design-principles. For the broader context, api-error-responses-guide and json-vs-yaml-vs-toml.

Frequently asked questions

What is JSON Schema?
A vocabulary for describing the structure of a JSON document, written in JSON itself. A validator checks a document against the schema and reports the errors. It is used for an API payload, a config file, and a form definition.
What is the difference between required and a property?
properties lists the allowed keys and their schemas, and required lists the keys that must be present. A key in properties but not in required is optional. A key in neither is rejected if additionalProperties is false.
What is the difference between anyOf, oneOf and allOf?
allOf requires every subschema to match, anyOf requires at least one, and oneOf requires exactly one. oneOf is the strictest and the most surprising, because a document that matches two subschemas fails.
What is additionalProperties?
A keyword that controls a key not listed in properties. false rejects an unknown key, which is the strict choice for an API. true allows it, and a schema allows it with a constraint. The default is true, which is a common surprise.
Can I generate code from a schema?
Yes. A tool can generate a TypeScript type, a Go struct, a Python model, or a form. The schema is the source of truth, and the generated code is derived. That keeps the validation and the type in sync.
What is a $ref?
A reference to another part of the schema, or to another schema by URL. It avoids a duplication and lets a large schema be split into files. A local reference uses a JSON Pointer such as #/definitions/User.