JSON Schema Basics: Validate Data Before Your Code Uses It

JSON can be syntactically valid while still being the wrong shape for an application. A missing field, a string where a number is expected, or an unexpected nested object may not be discovered until much later. JSON Schema provides a structured way to describe the data an application expects.

What a schema checks

A schema can declare which object properties are required, the accepted type of each value, allowed values and simple constraints such as a minimum length. It is useful at API boundaries, when checking configuration files and when documenting payloads shared between teams.

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "name": { "type": "string", "minLength": 1 },
    "retry": { "type": "integer", "minimum": 0 },
    "enabled": { "type": "boolean" }
  },
  "required": ["name", "enabled"],
  "additionalProperties": false
}

This schema accepts an object with a non-empty name, a non-negative integer retry when present, and a boolean enabled. It rejects an object without name or enabled, and it also rejects unknown properties because additionalProperties is false.

Start with the contract, not the syntax

Before writing a schema, list the values the receiving code truly needs. Separate required values from optional values. Decide whether empty text has a useful meaning, whether zero differs from a missing number and whether additional fields should be preserved or rejected. These decisions are the data contract; the schema merely makes them machine-checkable.

What JSON Schema does not do

Schema validation does not prove that a value is correct in the business sense. A date-shaped string can still be an impossible date, and an authorized-looking identifier may not exist in a database. Treat schema validation as an early, precise check—not a replacement for application logic, permission checks or tests.

Practical workflow: validate the original JSON, display clear errors to the person or system that sent it, then convert or process only the data that passed the expected contract.

Keep schemas maintainable

Name reusable pieces, keep error messages close to the field they describe and version an API deliberately when a breaking change is required. If you receive third-party data, allow only the fields you understand unless there is a reason to retain unknown values. A small schema that matches real code is more useful than a large theoretical one.

Next steps

Use the official JSON Schema documentation to choose the draft and validator appropriate for your stack. Before designing a schema, format a small sample with the JSON Formatter and read our guide to common JSON validation errors.