Validating JSON with JSON Schema: A Practical Guide

How to define and validate JSON data structures using JSON Schema.

validationschemabest-practices

JSON Schema

JSON Schema is a vocabulary for validating JSON documents. It describes the structure and constraints of your data.

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"]
}

Type Keywords

{ "type": "string" }
{ "type": "number" }
{ "type": "integer" }
{ "type": "boolean" }
{ "type": "null" }
{ "type": "array" }
{ "type": "object" }
{ "type": ["string", "null"] } // Multiple types

String Constraints

{
"type": "string",
"minLength": 1,
"maxLength": 100,
"pattern": "^[A-Za-z]+$",
"format": "email"
}

Number Constraints

{
"type": "number",
"minimum": 0,
"maximum": 100,
"exclusiveMinimum": 0,
"multipleOf": 0.01
}

Array Constraints

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

Validation in JavaScript

import Ajv from 'ajv';

const ajv = new Ajv();

const schema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'integer', minimum: 0 }
},
required: ['name']
};

const validate = ajv.compile(schema);

const valid = validate({ name: 'John', age: 30 });
// true

const invalid = validate({ age: -5 });
// false
console.log(validate.errors);
// [{ keyword: 'required', ... }, { keyword: 'minimum', ... }]