Skip to main content

Introduction to JSON Schema

Learning Focus

JSON Schema is a vocabulary for describing and validating JSON documents — a type system for your data.

What is JSON Schema?

JSON Schema is itself a JSON document that defines the expected structure, types, and constraints of another JSON document.

TermMeaning
SchemaThe JSON doc that describes the rules
InstanceThe JSON doc being validated
DraftA version of the JSON Schema specification

Current standard: Draft 2020-12

First Schema

user.schema.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.com/user.schema.json",
"title": "User",
"type": "object",
"properties": {
"id": { "type": "integer" },
"username": { "type": "string", "minLength": 3, "maxLength": 30 },
"email": { "type": "string", "format": "email" },
"isActive": { "type": "boolean" }
},
"required": ["id", "username", "email"]
}

Core Keywords

KeywordPurpose
typeData type constraint
propertiesDefine object fields
requiredMandatory fields array
enumAllowed values set
minimum / maximumNumeric range
minLength / maxLengthString length
patternString regex
formatSemantic format hint (email, date-time)
itemsArray element schema
$refReference another schema
additionalPropertiesAllow or deny extra keys

Python Validation

# pip install jsonschema
import jsonschema

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

try:
jsonschema.validate({"name": "Alice", "age": 30}, schema)
print("Valid!")
except jsonschema.ValidationError as e:
print(f"Invalid: {e.message}")

Concept Map

Concept Flow

JSON Schema
├── type → Validates data types
├── properties → Defines object structure
├── required → Enforces mandatory fields
├── format → Semantic format hints (email, date-time)
└── $ref → Reusable sub-schemas

Common Pitfalls

PitfallConsequencePrevention
format is advisory onlyValidators may skip checksUse ajv with validateFormats: true
Missing $schemaTools can't infer the draftAlways include $schema
type: "null" for optional fieldsPrevents useful valuesUse ["string", "null"] union type
No $ref for shared structuresMassive duplicationFactor into $defs and reference

What's Next