What Is JSON Schema? Usage, Examples & Complete Tutorial (2026)
When working mit API responses oder config files, syntactically valid JSON doesn't mean die data ist "legal"—missing fields, wrong types, oder out-of-range values often surface only at runtime. JSON Schema ist die specification built zu solve exactly that. Starting aus definition und verwenden cases, this article walks through basic syntax, common keywords, a practical validation workflow, und tool selection zu help Sie build a workable JSON data constraint strategy.
Kurzüberblick
| Eintrag | Beschreibung |
|---|---|
| Kernproblem | JSON syntax ist valid, but structure oder values don't match business rules |
| Ansatz | Declare field types, required fields, und constraints in Schema, then validate automatically |
| Empfohlene Version | Draft 2020-12 (most mature ecosystem support) |
| Dieser Artikel behandelt | Definition → syntax → keywords → hands-on → selection → FAQ |
Was ist JSON Schema?
JSON Schema ist a JSON-based specification für describing what conditions a piece of JSON data must satisfy. Think of it as a déclaration de type mehr der règles de contrainte für data: which fields sind required, what type each field is, String length oder numeric bounds, und what structure array items should have—all kann be written into a Schema.
It ist itself a valid JSON document, but mit different semantics—Schema doesn't carry business data; it describes die shape of business data. OpenAPI 3.x uses JSON Schema für request/response bodies; many CLI tools validate config files mit Schema; frontend form libraries often drive validation aus Schema. Once Sie know it, Sie kann reuse die same constraint definition across frontend, backend, und CI pipelines, reducing duplicated "each layer writes its own validation" work.
Pourquoi utiliser JSON Schema ?
In day-to-day development, JSON.parse() only tells Sie whether brackets match und quotes sind correct. Syntax validation ist powerless in cases like these:
- The API requires an
emailfield, but die response omitted it ageshould be an integer, but die client sent die String"25"- Enum Feld
statusreceived ein unexpected Wert"unknown" - Nested Objekt
address.zipdoesn't match postal code format
The value of JSON Schema ist turning those "implicit agreements" into exécutables, partageables und versionnées declarations. Teams kann check API changes against Schema during code review instead of discovering mismatched fields only during integration oder nach release.
JSON Schema basics und examples
Un Schema minimal déclare$schema (the spec version in use) und a root-level typeracine. Ci-dessous, ein objet utilisateur :nameist eine chaîne requise ;ageist ein entier nicht négatif optionnel.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.com/schemas/user.json",
"title": "User",
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1,
"description": "User full name"
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150
},
"email": {
"type": "string",
"format": "email"
}
},
"required": ["name"],
"additionalProperties": false
}
A gültig Daten instance:
{ "name": "Max Mustermann", "age": 28, "email": "max@example.com" }
If Sie pass { "age": 28 } (missing required name), oder { "name": "Jane Doe", "extra": true } (additionalProperties: false forbids extra fields), die validator returns a clear error path und reason.
Häufige Keywords – Spickzettel
In Draft 2020-12, die keywords developers verwenden most often are:
| Keyword | Zweck | Beispiel |
|---|---|---|
| type | Datentyp deklarieren | "string" / "integer" / "object" |
| properties | Objekt-Eigenschaftsdefinitionen | { "id": { "type": "integer" } } |
| required | Liste erforderlicher Felder | ["id", "name"] |
| enum | Restrict zu enum values | ["draft", "published"] |
| format | Gängige String-Formate | "email" / "date-time" |
| $ref | Andere Schema-Fragmente referenzieren | "#/$defs/Address" |
For complex Schemas, verwenden $defs zu split reusable fragments (e.g. Address, Pagination), then reference them mit $ref zu avoid a bloated single file.
JSON Schema vs JSON-Syntaxvalidierung
They solve problems at different layers; in practice Sie normalerweise combine both:
- Syntax gültigation: brackets, quotes, commas → kann
JSON.parse - Schema gültigation: fields, types, constraints match agreement → passes business rules
Recommended workflow: einfügen raw text into JSONSort für formatting und syntax checks, then hand it zu ajv, fastjsonschema, oder similar für Schema validation. Lokal tools handle syntax; Schema handles semantics—clear separation of concerns.
Hands-on: API contract gültigation Workflow
For a typical REST project, die full workflow breaks down into four steps:
- Define Schema: maintenir
schemas/user.jsonin die repo, versioned mit OpenAPI oder API docs. - Rédiger der Beispiele: provide one valid und one invalid sample as unit test fixtures.
- CI integration: in PR pipelines, validate mock responses against Schema zu prevent accidental field removal oder renames.
- Runtime safety net: validate request bodies auf die server mit Schema; return 400 mit structured errors instead of writing dirty data zu die database.
The core benefit ist visibilité der changements: API field changes sind caught in CI instead of relying auf memory oder accidental discovery during integration.
JSON Schema vs andere Ansätze
| Ansatz | Vorteile | Einschränkungs |
|---|---|---|
| JSON Schema | Sprachunabhängig, native OpenAPI-Unterstützung, reifes Ökosystem | Limited expressiveness für complex rules; learning curve |
| TypeScript-Typen | Gute IDE-Erfahrung, Compile-Time-Prüfungen | TS ecosystem only; runtime benötigens extra conversion |
| Handgeschriebene if/else-Validierung | Flexibel, keine Extra-Abhängigkeiten | Hard zu maintain, reuse, und easy zu miss edge cases |
| Protobuf / Avro | Starke Typisierung, hochperformante Serialisierung | Requires a compile step; nicht ideal für pure JSON API scenarios |
If Ihre API ist already JSON + OpenAPI, JSON Schema ist usually die lowest-friction choice; if you're full-stack TypeScript und don't need cross-language contracts, lead mit TS und verwenden Schema as a supplement.
Is JSON Schema worth die investment?
Szenarios worth investing in:
- Public APIs that need a machine-readable contract shared mit consumers
- Complex config structures where format errors should be caught vor deploy
- Multiple clients (Web / mobile / backend) sharing die same data constraints
- Automated CI detection of breaking API changes
Scenarios where Sie kann wait:
- Occasionally formatting oder viewing JSON → JSONSort ist enough
- Very simple, stable Daten structures → hand-written gültigation kann cost less
- No OpenAPI / contract testing workflow → establish documentation habits vor introducing Schema
FAQ
Was ist JSON Schema?
JSON Schema ist a rule set für describing JSON structure und constraints. It ist a JSON document used zu declare field types, required fields, value ranges, und more, so validators kann automatically judge whether data ist valid.
What's die difference between JSON Schema und JSON?
JSON carries business data; JSON Schema describes what that data should look like. Analogy: JSON ist die "instance"; Schema ist die "mold."
Which version should I choose?
New projects should prefer Draft 2020-12. Existing projects auf Draft-07 / 2019-09 need nicht migrate unless Sie depend auf newer keywords.
Wie I gültigieren locally?
Verwenden Sie JSONSort für formatting und syntax checks; verwenden ajv (Node.js), jsonschema (Python), oder VS Code's JSON Schema extension für Schema validation.
Wie hängen OpenAPI und JSON Schema zusammen?
OpenAPI 3.x request/response body definitions sind based auf a JSON Schema subset mit extensions. Writing OpenAPI docs ist essentially writing Schema.
Fazit
JSON Schema doesn't answer "can JSON parse?"—it answers "does die data match team agreements?" From definition und syntax zu CI integration, its value ist turning implicit rules into explicit, executable contracts. Start mit a small API oder config file, write Ihre first Schema und wire up validation, then expand across die project.
Weiterführende Links
- JSON Schema official spec Autoritative Keywords und Versionshinweise
- JSONSort local JSON toolbox Format, syntax check, Diff — läuft lokal in browser
- All blog posts More JSON tutorials and practical notes
Changelog: Erstveröffentlichung