JSON Schema is a standard way to describe what valid JSON looks like: which fields exist, what type each one is, and what values are allowed. Once you have a schema you can validate incoming data, generate documentation, and catch mistakes before they reach your code.
A first schema
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"name": { "type": "string", "minLength": 1 },
"age": { "type": "integer", "minimum": 0 },
"role": { "enum": ["admin", "user"] },
"tags": { "type": "array", "items": { "type": "string" } }
},
"required": ["name", "role"],
"additionalProperties": false
}
The keywords you'll use most
- type: string, number, integer, boolean, object, array, or null.
- properties: describes the fields of an object; required lists which ones must be present.
- items: describes the elements of an array.
- enum: restricts a value to a fixed list; const requires an exact value.
- minimum and maximum for numbers; minLength, maxLength, and pattern for strings.
- additionalProperties: false rejects fields you didn't list, which catches typos.
Generate first, then refine
The quickest way to start is to paste a sample document into a generator that infers a schema, then tighten it by hand. A generator can only see your example, so it won't know which fields are optional or what ranges are valid.
- Generate a schema from a representative sample.
- Mark truly required fields in required.
- Add constraints: ranges, lengths, enums, and formats.
- Validate both good and deliberately bad samples to make sure the schema rejects what it should.
Good habits
- State the draft with $schema so tools know which rules to apply. Draft 2020-12 is the current one.
- Reuse repeated shapes with $defs and $ref instead of copy-pasting.
- Keep schemas in version control next to the code that depends on them.
- Remember that a schema validates structure, not business rules such as "end date after start date".
Validate on the server too
Client-side validation improves the experience, but anything that arrives over the network should be validated again on the server.
Frequently asked questions
What is JSON Schema used for?
Validating JSON data, documenting APIs, generating forms, and catching bad input early.
How do I make a field optional?
List it under properties but leave it out of the required array.
Which JSON Schema draft should I use?
The latest is 2020-12, which is a good default. Older drafts such as 7 are still common in existing tools.
Can a schema check that two fields relate to each other?
Only in limited ways, using keywords like dependentRequired or if/then. Complex business rules belong in code.
Try it: JSON Schema Generator — free, runs in your browser, nothing is uploaded.
Originally published at ilovekit.app.
Top comments (0)