DevLab
JSON

JSON Schema Explained: Validate Your JSON Data

Learn how JSON Schema works, how to write validation rules for objects and arrays, and how to use it for API request validation and OpenAPI documentation.

What is JSON Schema?

JSON Schema is a vocabulary for describing the structure of JSON data. It is itself a JSON document that defines what other JSON documents should look like — their types, required fields, allowed values, and nested structures. Think of it as a type system for JSON that works at runtime, without compilation.

Basic Structure

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

Type Keywords

  • "type": "string" — any string value
  • "type": "number" — integer or float
  • "type": "integer" — whole numbers only
  • "type": "boolean" — true or false
  • "type": "array" — JSON array
  • "type": "object" — JSON object with key-value pairs

Common Constraints

// Strings
"minLength": 1, "maxLength": 100
"pattern": "^[a-z0-9-]+$"

// Numbers
"minimum": 0, "maximum": 100
"multipleOf": 5

// Arrays
"items": { "type": "string" }
"minItems": 1, "maxItems": 10
"uniqueItems": true

// Enums
"enum": ["active", "inactive", "pending"]

Reusable Definitions with $ref

{
  "type": "object",
  "properties": {
    "address": { "$ref": "#/$defs/Address" }
  },
  "$defs": {
    "Address": {
      "type": "object",
      "properties": {
        "street": { "type": "string" },
        "city":   { "type": "string" }
      },
      "required": ["street", "city"]
    }
  }
}

Practical Uses

  • API request validation: Libraries like Zod, Yup, and Ajv validate request bodies against a schema at runtime
  • Documentation: OpenAPI/Swagger uses JSON Schema to document request and response shapes
  • IDE autocomplete: VS Code uses JSON Schema to provide autocomplete for tsconfig.json, package.json, and other config files
  • Database input sanitization: Validate data before inserting to catch type mismatches early

Practice with these tools

More Learning Topics