JSON Schema
JSON.parse() tells you whether text is syntactically valid JSON. It says nothing about whether the data makes sense: {"age": "very old"} parses perfectly. JSON Schema is a standard vocabulary for describing what valid data looks like — which keys are required, which types they have, which values are allowed — written, fittingly, in JSON itself.
A first schema
Here is a schema for a user record:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "User",
"type": "object",
"properties": {
"username": {"type": "string", "minLength": 3},
"age": {"type": "integer", "minimum": 0},
"email": {"type": "string", "format": "email"},
"roles": {
"type": "array",
"items": {"enum": ["admin", "editor", "viewer"]}
}
},
"required": ["username", "email"],
"additionalProperties": false
}Valid JSON: object with 6 keys
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "User",
"type": "object",
"properties": {
"username": {
"type": "string",
"minLength": 3
},
"age": {
"type": "integer",
"minimum": 0
},
"email": {
"type": "string",
"format": "email"
},
"roles": {
"type": "array",
"items": {
"enum": [
"admin",
"editor",
"viewer"
]
}
}
},
"required": [
"username",
"email"
],
"additionalProperties": false
}
Read it as: "A user is an object. username is a string of at least 3 characters, age is a non-negative integer, email is a string in email format, roles is an array whose items are one of three words. username and email must be present, and no other keys are allowed."
The most common keywords
| Keyword | Applies to | Meaning |
|---|---|---|
type |
any | "string", "number", "integer", "boolean", "null", "object", "array" (or a list of them) |
enum / const |
any | Value must be one of a list / exactly this value |
properties |
object | Schemas for individual keys |
required |
object | Keys that must be present |
additionalProperties |
object | false forbids unknown keys |
items |
array | Schema every item must match |
minItems / maxItems |
array | Length limits |
minLength / maxLength / pattern |
string | Length limits / regex |
minimum / maximum |
number | Range limits (inclusive) |
format |
string | Hints like "email", "date-time", "uri" |
$ref |
any | Reuse a schema defined elsewhere |
Valid and invalid data
This record matches the schema above:
{"username": "mai", "email": "mai@example.com", "age": 27, "roles": ["editor"]}These do not:
| Data | Why it fails |
|---|---|
{"username": "mai"} |
email is required |
{"username": "jo", "email": "jo@x.io"} |
username shorter than 3 |
{"username": "mai", "email": "m@x.io", "age": -1} |
age below minimum |
{"username": "mai", "email": "m@x.io", "roles": ["owner"]} |
"owner" not in enum |
{"username": "mai", "email": "m@x.io", "admin": true} |
extra key not allowed |
A small validator by hand
Real projects use a library such as Ajv (JavaScript) or jsonschema (Python). But the core idea is simple enough to build yourself. This mini validator supports a subset of keywords and reports every problem with its path:
function typeOf(v) {
if (v === null) return "null";
if (Array.isArray(v)) return "array";
if (Number.isInteger(v)) return "integer";
return typeof v;
}
function validate(schema, data, path = "quot;, errors = []) {
const t = typeOf(data);
if (schema.type) {
const ok = schema.type === t || (schema.type === "number" && t === "integer");
if (!ok) { errors.push(`${path}: expected ${schema.type}, got ${t}`); return errors; }
}
if (schema.enum && !schema.enum.includes(data)) {
errors.push(`${path}: must be one of ${schema.enum.join(", ")}`);
}
if (t === "string" && data.length < (schema.minLength ?? 0)) {
errors.push(`${path}: shorter than ${schema.minLength}`);
}
if ((t === "integer" || t === "number") && schema.minimum !== undefined && data < schema.minimum) {
errors.push(`${path}: less than ${schema.minimum}`);
}
if (t === "object") {
for (const key of schema.required ?? []) {
if (!(key in data)) errors.push(`${path}: missing required "${key}"`);
}
for (const [key, value] of Object.entries(data)) {
const sub = schema.properties?.[key];
if (sub) validate(sub, value, `${path}.${key}`, errors);
else if (schema.additionalProperties === false) errors.push(`${path}: unexpected key "${key}"`);
}
}
if (t === "array" && schema.items) {
data.forEach((item, i) => validate(schema.items, item, `${path}[${i}]`, errors));
}
return errors;
}
const userSchema = {
type: "object",
properties: {
username: { type: "string", minLength: 3 },
age: { type: "integer", minimum: 0 },
email: { type: "string" },
roles: { type: "array", items: { enum: ["admin", "editor", "viewer"] } },
},
required: ["username", "email"],
additionalProperties: false,
};
const samples = [
'{"username": "mai", "email": "mai@example.com", "age": 27, "roles": ["editor"]}',
'{"username": "jo", "age": -1, "roles": ["viewer", "owner"], "admin": true}',
'{"username": "lan", "email": "lan@example.com", "age": "27"}',
];
for (const text of samples) {
const errors = validate(userSchema, JSON.parse(text));
console.log(errors.length ? errors.join("\n") : "valid");
console.log("--");
}valid
--
$: missing required "email"
$.username: shorter than 3
$.age: less than 0
$.roles[1]: must be one of admin, editor, viewer
$: unexpected key "admin"
--
$.age: expected integer, got string
--
Notice that "27" (a string) is rejected for age — exactly the kind of mistake JSON.parse lets through.
Reusing definitions with $ref
Schemas can define shared pieces under $defs and refer to them with $ref, so an address shape is written once and used twice:
{
"type": "object",
"properties": {
"billing": {"$ref": "#/$defs/address"},
"shipping": {"$ref": "#/$defs/address"}
},
"$defs": {
"address": {
"type": "object",
"properties": {
"street": {"type": "string"},
"city": {"type": "string"}
},
"required": ["street", "city"]
}
}
}Valid JSON: object with 3 keys
{
"type": "object",
"properties": {
"billing": {
"$ref": "#/$defs/address"
},
"shipping": {
"$ref": "#/$defs/address"
}
},
"$defs": {
"address": {
"type": "object",
"properties": {
"street": {
"type": "string"
},
"city": {
"type": "string"
}
},
"required": [
"street",
"city"
]
}
}
}
Validating in Python
With the third-party jsonschema package (pip install jsonschema), validation is one call:
from jsonschema import validate, ValidationError
schema = {"type": "object", "required": ["id"], "properties": {"id": {"type": "integer"}}}
try:
validate({"id": "7"}, schema)
except ValidationError as err:
print(err.message) # '7' is not of type 'integer'Why bother?
- Validate input at the edge of your system — API requests, uploaded files, config files — and give clear error messages.
- Document your data: a schema is precise, machine-readable documentation.
- Editor support: VS Code reads
$schemaand offers autocompletion and error underlines in JSON files. - Code generation: tools generate TypeScript types, forms or API docs (OpenAPI uses JSON Schema) from schemas.
Test yourself
What does JSON Schema check that JSON.parse does not?
- Whether brackets match
- Whether the data has the expected structure, types and values
- Whether the file is UTF-8
- Whether keys are quoted
Which keyword lists keys that must be present in an object?
- properties
- mandatory
- required
- keys
What does "additionalProperties": false do?
- Makes all properties optional
- Forbids keys not listed in
properties - Removes unknown keys automatically
- Allows any extra keys