2026-02-05|JSON

JSON Schema Validation: Ensure Data Quality and Consistency

JSON Schema for Data Validation

JSON Schema is a powerful vocabulary that allows you to annotate and validate JSON documents. It defines the structure, types, and constraints of your data, ensuring consistency and reliability across your applications.

Basic Schema Structure

A JSON Schema is itself a JSON document that describes the expected structure:

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

Data Types

JSON Schema supports these fundamental types:

  • string - Text values with optional pattern matching
  • number - Integer and floating-point values
  • integer - Whole numbers only
  • boolean - true or false
  • array - Ordered list of items
  • object - Key-value pairs
  • null - The null value

Constraining String Values

Use format and pattern for string validation:

{
  "email": {
    "type": "string",
    "format": "email",
    "maxLength": 255
  },
  "username": {
    "type": "string",
    "pattern": "^[a-zA-Z0-9_]{3,20}$"
  }
}

Required Fields and Dependencies

Mark fields as required to enforce their presence. Use dependentRequired for conditional requirements:

{
  "required": ["name", "email"],
  "dependentRequired": {
    "shippingAddress": ["billingAddress"]
  }
}

Array Validation

Control array contents with items, minItems, and maxItems:

{
  "tags": {
    "type": "array",
    "items": { "type": "string", "minLength": 1 },
    "minItems": 1,
    "maxItems": 10,
    "uniqueItems": true
  }
}

Custom Validators

Many libraries support custom keyword validators for business logic:

const Ajv = require("ajv");
const ajv = new Ajv();

ajv.addKeyword({
  keyword: "isPositive",
  validate: (schema, data) => data > 0,
  errors: false
});

Integration

Popular libraries like Ajv (JavaScript), jsonschema (Python), and jsonschema (Go) make it easy to validate data at runtime, protecting your APIs and databases from malformed input.