What is JSON Schema?
JSON Schema is a meta-language to describe what a JSON document should look like. You
define types (string, integer, object,
array), required properties, min and max values, formats (email, date-time,
uri) and regex patterns. Validators like Ajv check a payload against the schema and report
errors with exact paths.
Basic structure
A schema starts with $schema pointing to the draft, $id with a
unique URI, and type declaring the root type. For an object,
properties lists each field and required the mandatory ones.
additionalProperties: false rejects undeclared fields; useful for catching typos.
Common formats
- email: validates an RFC 5322 email.
- date-time: ISO 8601 (e.g. 2024-01-15T10:30:00Z).
- date: date only (2024-01-15).
- uuid: UUID v1-v8.
- uri: valid URL.
- ipv4, ipv6: IP addresses.
String validation
minLength, maxLength and pattern (regex) are your
friends. Phone example:
"pattern": "^\\+?[0-9]{9,15}$". enum limits to a fixed
set: "enum": ["pending", "paid", "shipped"].
Number validation
minimum, maximum, exclusiveMinimum,
exclusiveMaximum and multipleOf. For prices:
"minimum": 0, "multipleOf": 0.01. Use integer instead of
number to reject decimals.
Array validation
items describes the schema of each element. minItems,
maxItems and uniqueItems are useful for lists. For arrays with
positional types (tuples), use prefixItems in draft 2020-12.
Combinations: oneOf, anyOf, allOf
oneOf requires matching exactly one; useful for discriminated unions.
anyOf matches one or more. allOf requires all; used to extend
schemas. not negates a schema.
From schema to types
json-schema-to-typescript turns a schema into TS interfaces. You keep one
source of truth: the schema validates at runtime, types guard the code. The reverse,
generating schemas from TS, is available via typescript-json-schema or
ts-json-schema-generator.