Your service accepts product data from partners. One partner sends "price": "49.50" as a string, another forgets name, a third adds fields nobody asked for. You want a machine-readable contract that says exactly what a valid product looks like, so you can reject bad data at the door and share the rules with everyone who integrates.
That contract is a JSON Schema. Writing one from scratch is tedious, but generating a first draft from a real sample takes seconds. This guide explains what JSON Schema is, how to pick a draft version, how to generate a schema, and which parts you should always tighten by hand afterwards.
What JSON Schema is
JSON Schema is itself a JSON document that describes other JSON documents. A validator reads the schema and a piece of data and tells you whether the data conforms, and if not, why. A minimal schema for a product looks like this:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"name": { "type": "string" },
"price": { "type": "number" },
"stock": { "type": "integer" }
},
"required": ["name", "price"],
"additionalProperties": false
}
The core keywords you will meet in almost every schema:
type:string,number,integer,boolean,null,objectorarray, or a list of them.properties: a schema for each named key of an object.required: which keys must be present. Keys not listed are optional.additionalProperties: whether keys not listed inpropertiesare allowed. Set tofalseto reject unknown keys.items: the schema every element of an array must match.format: a hint such asemail,date,date-time,urioruuid.enum,minimum,maxLength,pattern: constraints you add by hand.
Schemas are used for validating API requests, documenting payloads in OpenAPI, giving editors autocomplete for config files, and generating forms.
Draft 2020-12 or draft-07?
JSON Schema has gone through several versions, called drafts. The $schema keyword at the top declares which one a schema uses. For generated schemas, two matter in practice:
| Draft-07 | Draft 2020-12 | |
|---|---|---|
$schema URI |
http://json-schema.org/draft-07/schema# |
https://json-schema.org/draft/2020-12/schema |
| Reusable definitions | definitions by convention |
$defs |
| Tuples (fixed positions) | items as an array, plus additionalItems |
prefixItems, with items for the rest |
| Conditional requirements | dependencies |
dependentRequired, dependentSchemas |
| Extra keywords | none of the newer ones | unevaluatedProperties, unevaluatedItems |
For the simple object, array and type keywords a generator produces, both drafts look almost identical. The choice comes down to your tooling:
- Choose 2020-12 for new projects and anything built on OpenAPI 3.1, which is aligned with it.
- Choose draft-07 when an older validator, library or platform only supports that version. It has been around for a long time and support for it is very broad.
Check your validator's documentation for which drafts it supports. In Node.js, for example, the widely used Ajv library has a separate class for 2020-12 schemas, imported from ajv/dist/2020.
Generate a schema with our tool
- Open the JSON Schema Generator and paste a representative example into JSON sample, or use Open file or Load sample.
- Pick the Draft: Draft 2020-12 or Draft-07.
- Set an optional Title, such as
Product. It becomes the schema'stitle. - Choose the switches:
- Require every field marks all observed keys as required.
- No additional properties adds
"additionalProperties": falseto every object. - Detect formats (email, date, uri…) adds a
formatwhen every sample value matches one, for exampleemail,date,date-time,time,uuid,urioripv4.
- Review the JSON Schema output, then Copy it or Download it as a
.schema.jsonfile.
How "required" is decided
With a single object, every key in the sample is present, so every key ends up in required. The interesting case is an array of objects: the generator merges all items, and a key only counts as required if it appears in every item. Keys that appear in some items are left optional. Require every field overrides that and requires all of them.
That gives you a practical technique: collect several real payloads, wrap them in an array, and generate from that. The schema for the array's items then reflects which fields are truly always present.
Numbers are treated carefully too. If all samples are whole numbers the type is integer; if any has a fraction it becomes number. A field seen with different types gets a list such as "type": ["string", "null"], or an anyOf when objects or arrays are involved.
What to fix by hand after generating
A generated schema describes your sample, not your business rules. Before you use it to reject data, review these points.
Nullable fields. A key whose sample value is null gets "type": "null", which would reject any real value. Change it to, say, ["string", "null"].
Integers that should be numbers. A price of 50 in the sample becomes integer, and a later 49.5 would fail. Loosen it to number where decimals are allowed.
Enumerations. A status of "shipped" becomes just string. Add "enum": ["pending", "shipped", "cancelled"] if the set is closed.
Ranges and lengths. Add minimum: 0 to prices and stock, minLength: 1 to names, maxItems to arrays you store.
Formats are hints by default. Many validators treat format as an annotation and do not reject non-matching strings unless you enable format checking. Test your validator's behaviour, and use pattern when you need a guarantee.
Unknown keys. additionalProperties: false is strict. It catches typos such as prcie early, but it also means a client that starts sending a new optional field is rejected until the schema is updated. Decide deliberately which side of that trade-off suits each API.
Other ways to create a schema
- Write it by hand for small, stable payloads. You will think harder about every rule, which is the point of a contract.
- Generate from code. Many languages have libraries that emit JSON Schema from classes or validation rules, keeping the schema and code in sync.
- Use your API specification. If you maintain an OpenAPI document, its component schemas already are JSON Schema (in OpenAPI 3.1) and can be reused.
Sample-based generation is best as a starting point: fast, accurate for structure, and then refined by a person who knows the rules.
Related tools
If you also need static types for your code, generate them from the same sample with JSON to TypeScript. To check that a sample is well-formed before you start, use the JSON Validator, and to see what changed between two versions of a payload, use JSON Compare.
Frequently asked questions
What is the difference between JSON Schema drafts?
Each draft is a revision of the specification. Newer drafts renamed and added keywords, such as $defs and prefixItems in 2020-12. The $schema value at the top tells validators which rules to apply.
Which JSON Schema draft should I use?
Use draft 2020-12 for new work unless a tool you depend on only supports an older draft, in which case draft-07 is the most widely supported fallback.
Can a JSON Schema be generated from multiple examples?
Yes. Put the examples in one JSON array and generate from it. The items are merged, so fields missing from some examples become optional in the schema.
Does "format": "email" guarantee a valid email address?
No. Format checking is often optional in validators, and even when enabled it checks syntax, not whether the mailbox exists. Treat it as a first filter.
Is JSON Schema the same as a TypeScript interface?
They overlap but serve different purposes. TypeScript types are checked at compile time and vanish at runtime; JSON Schema is checked at runtime against real data and can express constraints like ranges and patterns.