JSON Schema Basics: Describe and Validate Your JSON
Updated · 6 min read · MetaSol Technologies
A JSON validator tells you whether text is valid JSON. It cannot tell you whether the data makes sense: {"age": "forty"}
is perfectly valid JSON, even if your application needs a number. JSON Schema describes what the data should look
like, so mistakes are caught before they reach your code, your database or your customers.
A first schema
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["id", "email"],
"properties": {
"id": { "type": "integer", "minimum": 1 },
"email": { "type": "string", "format": "email" },
"plan": { "enum": ["free", "team", "enterprise"] }
},
"additionalProperties": false
}
This says: the data is an object; id and email must be present; id is a whole number from 1 upwards; email
looks like an email address; plan, if present, is one of three values; and no other fields are allowed.
The building blocks
| Keyword | What it checks | Example |
|---|---|---|
type |
string, number, integer, boolean, object, array, null | "type": "string" |
required |
fields that must exist | "required": ["id"] |
properties |
a schema for each field | see above |
enum |
one of a fixed list | "enum": ["S", "M", "L"] |
minimum / maximum |
number ranges | "minimum": 0 |
minLength / maxLength / pattern |
string length and shape | "pattern": "^[A-Z]{3}$" |
format |
common formats | email, date-time, uri, uuid |
items |
a schema for every array item | "items": { "type": "string" } |
uniqueItems |
no duplicate array items | "uniqueItems": true |
additionalProperties |
allow or forbid extra fields | false catches typos in field names |
Reusing definitions
Put shared pieces under $defs and reference them with $ref:
{
"$defs": { "money": { "type": "number", "minimum": 0 } },
"properties": { "price": { "$ref": "#/$defs/money" }, "tax": { "$ref": "#/$defs/money" } }
}
Validating
Paste the schema and your data into the JSON Schema Validator. It lists every problem with the
path of the failing value (for example $.email), the rule that failed, and a readable message. It supports drafts 4,
7, 2019-09 and 2020-12. Use 2020-12 for new schemas.
Tips
- Start strict (
additionalProperties: false,required) and loosen deliberately. Strict schemas catch typos such asemialthat would otherwise slip through silently. - Keep the schema next to the code that produces the data, and validate in your tests as well as at runtime.
- Schemas double as documentation: many API tools generate forms and docs from them.