Chapter 8

JSON Schema Validation

Validating JSON data structure and types

What is JSON Schema?

JSON Schema is a declarative format for validating the structure, types, and constraints of JSON data. It acts as a "blueprint" or "rulebook" for JSON data.

💡 Uses: API validation, config file checking, data formatting, auto-generated documentation

Schema Example

Defining a Schema for a user object:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "name": {
      "type": "string",
      "minLength": 2,
      "maxLength": 50
    },
    "age": {
      "type": "integer",
      "minimum": 0,
      "maximum": 150
    },
    "email": {
      "type": "string",
      "format": "email"
    }
  },
  "required": ["name", "age"],
  "additionalProperties": false
}

✅ Valid Data

{"name": "John Doe", "age": 30, "email": "[email protected]"}

❌ Invalid Data

{"name": "Jane Smith"} (missing age)

Common Keywords

Type Constraints

  • type : Data Type
  • enum : Enum Values

Numeric Constraints

  • minimum/maximum : Min/Max
  • exclusiveMinimum : Exclusive Minimum

String Constraints

  • minLength/maxLength : Length
  • pattern : Regex Pattern
  • format : Predefined Format

Array Constraints

  • items : Item Type
  • minItems/maxItems : Count
  • uniqueItems : Uniqueness