JSON Schema: A Practical Guide

January 10, 20248 min read

JSON Schema is a powerful tool for validating the structure of JSON data. It allows you to specify what kind of data is expected, making it invaluable for API validation, configuration verification, and data quality assurance.

Basic Schema Structure

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

Type Keywords

JSON Schema supports these primitive types:

  • string
  • number / integer
  • boolean
  • null
  • object
  • array

String Constraints

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

Number Constraints

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

Array Constraints

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

Composition Keywords

Combine schemas using allOf, anyOf, oneOf, and not:

{
  "oneOf": [
    { "type": "string" },
    { "type": "number" }
  ]
}