What is JSON Schema?
JSON Schema is a vocabulary that allows you to validate the structure and content of JSON data. It's like TypeScript types for JSON — but more powerful and portable across languages.
Basic Schema Example
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150
},
"email": {
"type": "string",
"format": "email"
},
"tags": {
"type": "array",
"items": { "type": "string" },
"uniqueItems": true
}
},
"required": ["name", "email"],
"additionalProperties": false
}
This schema validates that:
nameis a string (1-100 chars)ageis an integer (0-150)emailis a valid email formattagsis an array of unique stringsnameandemailare required- No extra properties allowed
Common Validation Keywords
String Validation
minLength/maxLength— length constraintspattern— regex patternformat— predefined formats (email, uri, date, uuid)
Number Validation
minimum/maximum— value rangeexclusiveMinimum/exclusiveMaximum— exclusive rangemultipleOf— must be a multiple of a number
Array Validation
minItems/maxItems— array lengthuniqueItems— no duplicatesitems— schema for all itemsprefixItems— schema for specific positions
Object Validation
required— list of required propertiesproperties— schema for each propertyadditionalProperties— allow/disallow extra propertiesminProperties/maxProperties— property count
Advanced Features
Conditional Validation
{
"if": {
"properties": { "type": { "const": "business" } }
},
"then": {
"required": ["companyName", "taxId"]
},
"else": {
"required": ["firstName", "lastName"]
}
}
Combining Schemas
allOf— must match ALL schemasanyOf— must match at LEAST ONE schemaoneOf— must match EXACTLY ONE schemanot— must NOT match the schema
Reusable Definitions
{
"$defs": {
"address": {
"type": "object",
"properties": {
"street": { "type": "string" },
"city": { "type": "string" }
}
}
},
"properties": {
"home": { "$ref": "#/$defs/address" },
"work": { "$ref": "#/$defs/address" }
}
}
Using JSON Schema in Code
JavaScript/TypeScript (Ajv)
import Ajv from "ajv";
const ajv = new Ajv();
const validate = ajv.compile(schema);
const valid = validate(data);
if (!valid) console.log(validate.errors);
Python (jsonschema)
import jsonschema
jsonschema.validate(instance=data, schema=schema)
Conclusion
JSON Schema is the standard way to validate JSON data. It's used in APIs, configuration files, and data pipelines. Start with a simple schema and add complexity as needed.
Use our JSON Formatter to format your JSON before validating it against your schema.