PureTools

JSON Schema: Validate Your Data Automatically

PureTools Team· 7 min read
JSON Schema: Validate Your Data Automatically

JSON Schema: Define the Shape of Your Data

JSON Schema is a declarative way to validate JSON data. Instead of writing validation code, you define a schema, and a library checks if data conforms. Used in OpenAPI specs, config file validation, and API request/response validation.

Basic Schema

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "name": { "type": "string", "minLength": 1 },
    "email": { "type": "string", "format": "email" },
    "age": { "type": "integer", "minimum": 0, "maximum": 150 },
    "role": { "type": "string", "enum": ["admin", "user", "guest"] },
    "tags": {
      "type": "array",
      "items": { "type": "string" },
      "uniqueItems": true
    }
  },
  "required": ["name", "email"],
  "additionalProperties": false
}

Type Keywords

TypeValidation Keywords
stringminLength, maxLength, pattern, format
number/integerminimum, maximum, multipleOf
boolean—
arrayitems, minItems, maxItems, uniqueItems
objectproperties, required, additionalProperties
null—

Formats

{ "format": "email" }       // user@example.com
{ "format": "uri" }         // https://example.com
{ "format": "date" }        // 2026-04-23
{ "format": "date-time" }   // 2026-04-23T10:30:00Z
{ "format": "uuid" }        // 550e8400-e29b-41d4-a716-446655440000
{ "format": "ipv4" }        // 192.168.1.1
{ "format": "hostname" }    // example.com

Validation with Ajv (JavaScript)

import Ajv from 'ajv';
import addFormats from 'ajv-formats';

const ajv = new Ajv({ allErrors: true });
addFormats(ajv);

const schema = {
  type: 'object',
  properties: {
    email: { type: 'string', format: 'email' },
    age: { type: 'integer', minimum: 18 },
  },
  required: ['email'],
};

const validate = ajv.compile(schema);
const valid = validate({ email: 'test@example.com', age: 25 });

if (!valid) {
  console.log(validate.errors);
  // [{ keyword: 'required', params: { missingProperty: 'email' } }]
}

Nested Objects and References

{
  "type": "object",
  "properties": {
    "user": { "$ref": "#/$defs/User" },
    "items": {
      "type": "array",
      "items": { "$ref": "#/$defs/OrderItem" }
    }
  },
  "$defs": {
    "User": {
      "type": "object",
      "properties": {
        "name": { "type": "string" },
        "email": { "type": "string", "format": "email" }
      },
      "required": ["name", "email"]
    },
    "OrderItem": {
      "type": "object",
      "properties": {
        "productId": { "type": "string" },
        "quantity": { "type": "integer", "minimum": 1 }
      }
    }
  }
}

Validate your JSON: JSON Formatter — format and validate JSON data.