W tym artykule
What Is JSON Schema?
JSON Schema is a vocabulary for annotating and validating JSON documents. It defines the structure, types, and constraints that a JSON document must satisfy. Think of it as a contract — the schema describes what valid data looks like, and validators check whether a document conforms to that contract.
JSON Schema is written in JSON itself, making it machine-readable and language-agnostic. It is supported by validators in every major programming language (JavaScript/Ajv, Python/jsonschema, Java/everit, Go/gojsonschema) and is used for API validation, configuration files, and form generation.
JSON Schema Basics
The core keywords define the shape of valid JSON documents.
- type — specifies the allowed JSON type: string, number, integer, boolean, object, array, or null. The most fundamental constraint.
- properties and required — for objects, 'properties' defines each field's schema and 'required' lists which fields must be present. Fields not in 'required' are optional by default.
- enum and const — 'enum' restricts a value to a fixed set of choices, while 'const' restricts it to a single exact value. Useful for status fields, categories, and configuration options.
- pattern and format — 'pattern' validates strings against a regular expression. 'format' provides semantic validation like 'email', 'uri', 'date-time', and 'ipv4' without regex.
These basic keywords cover most validation needs. A simple schema might define an object type with required 'name' (string) and optional 'age' (integer, minimum 0) properties.
Advanced Schema Features
For complex validation requirements, JSON Schema offers composition, references, and conditional logic.
- $ref references — reuse schema definitions by referencing them with $ref. Point to definitions within the same document ($ref: #/$defs/Address) or external files. Eliminates duplication across large schemas.
- allOf / anyOf / oneOf — composition keywords that combine multiple schemas. 'allOf' requires all sub-schemas to match, 'anyOf' requires at least one, and 'oneOf' requires exactly one. Useful for polymorphic types.
- if / then / else — conditional schemas that apply different validation rules based on data values. For example, if country is 'US' then zip code must match a 5-digit pattern, else allow any format.
- additionalProperties — controls whether an object can contain properties not listed in 'properties'. Set to false for strict validation or to a schema to constrain extra properties.
Wypróbuj za darmo — bez rejestracji
Waliduj JSON Schema →Schema Draft Versions
JSON Schema has evolved through several draft versions, each adding new features and refining existing behavior.
- Draft-04 — the first widely adopted version. Introduced $ref, required as an array, and basic validation keywords. Still used in many legacy systems and OpenAPI 3.0.
- Draft-06 — added const keyword, propertyNames, contains for arrays, and boolean schemas (true/false as valid schemas). Minor but useful additions.
- Draft-07 — added if/then/else conditional logic, readOnly/writeOnly annotations, and content encoding keywords. The most popular draft version today.
- 2019-09 (Draft 2019-09) — major restructuring. Introduced $defs (replacing definitions), $anchor, unevaluatedProperties, and vocabulary system. Better for large-scale schema design.
- 2020-12 (Draft 2020-12) — the latest stable draft. Refined dynamic references, added prefixItems for tuple validation (replacing items as an array), and improved output formats. Recommended for new projects.
Common Use Cases
JSON Schema is used wherever JSON data needs to be validated or documented.
- API validation — validate request bodies and query parameters against schemas in Express/Fastify middleware. OpenAPI/Swagger specifications embed JSON Schema for API contract definition.
- Configuration validation — validate application config files (JSON, YAML converted to JSON) at startup. Catch typos and missing fields before they cause runtime errors.
- Form generation — tools like react-jsonschema-form and vue-jsonschema-form auto-generate HTML forms from JSON Schema definitions, including validation rules and UI widgets.
- Code generation — generate TypeScript interfaces, Go structs, or Python dataclasses from JSON Schema definitions. Keeps types in sync with API contracts.
Common Validation Errors
When validating JSON against a schema, these are the most frequent errors you will encounter.
- Type mismatch — the value type does not match the schema's 'type' constraint. Common examples: string where number is expected, null for a non-nullable field, or an object where an array is required.
- Missing required fields — the JSON object is missing a property listed in the 'required' array. Validators report which specific field is missing.
- Pattern failure — a string value does not match the 'pattern' regex. This often catches invalid email formats, phone numbers, or custom identifiers that do not follow the expected pattern.
- $ref resolution failure — the schema references another schema via $ref that cannot be found. This happens when a $defs entry is missing, the path is wrong, or external schema files are not accessible.
Frequently Asked Questions
Which JSON Schema draft should I use for new projects?
Use Draft 2020-12 for new projects unless you have constraints. It has the most features (prefixItems for tuples, unevaluatedProperties, dynamic references) and the best specification quality. If you need OpenAPI 3.0 compatibility, use Draft-04. If you need the widest library support, Draft-07 is the safest choice — almost every validator supports it.
How do I reuse schemas across multiple files?
Use $ref to reference schemas by URI. For local definitions, place reusable schemas under $defs in the same file and reference them with $ref: '#/$defs/SchemaName'. For cross-file references, use relative URIs ($ref: './address.json') or absolute URIs. Most validators support both local and remote $ref resolution.
Can JSON Schema validate nested objects?
Yes. Define nested schemas in the 'properties' of the parent object. Each nested property can have its own type, required fields, and validation rules. For deeply nested structures, use $ref to keep the schema readable. There is no limit to nesting depth — the validator recursively validates each level.