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.
| Term | Meaning |
|---|---|
| Schema | The JSON doc that describes the rules |
| Instance | The JSON doc being validated |
| Draft | A 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
| Keyword | Purpose |
|---|---|
type | Data type constraint |
properties | Define object fields |
required | Mandatory fields array |
enum | Allowed values set |
minimum / maximum | Numeric range |
minLength / maxLength | String length |
pattern | String regex |
format | Semantic format hint (email, date-time) |
items | Array element schema |
$ref | Reference another schema |
additionalProperties | Allow 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
| Pitfall | Consequence | Prevention |
|---|---|---|
format is advisory only | Validators may skip checks | Use ajv with validateFormats: true |
Missing $schema | Tools can't infer the draft | Always include $schema |
type: "null" for optional fields | Prevents useful values | Use ["string", "null"] union type |
No $ref for shared structures | Massive duplication | Factor into $defs and reference |
What's Next
- Next: Advanced Schema Keywords — Composition, conditionals, and
$ref. - Section Overview — Return to the JSON Schema module index.