Skip to main content
CuteJSON
↑↓ Navigate Enter Select Esc Close

JSON Schema validation explained, keyword by keyword

Published 20 min read By Akash Kinkar Pandey

You have a schema. Your JSON still gets rejected at 2am by a library you did not write, and when you open the error it names a keyword you have never heard of. Or worse, the document ships, and three weeks later the consumer of your API complains that price arrived as the string "8.95" and broke their spreadsheet. The schema you wrote weeks ago probably says "type": "number" on that field. It validated. So what went wrong?

Almost always this: one of a handful of keywords behaved the way the specification says it behaves, not the way you assumed. JSON Schema validation is not one rule. It is many small rules applied independently, and knowing which keyword does what turns panic into a ten-second fix.

This article walks through the keywords that decide anything, the mistakes that trip up almost everyone, how the drafts differ, and how to read a validation error when one lands.

Key Takeaways

  • Each JSON Schema keyword applies on its own. A type match does not stop pattern, enum or minimum from also being checked, so a document needs to satisfy every keyword on the same object.
  • type: "integer" accepts 1.0 under draft 2020-12, because the spec defines integers as numbers with a zero fractional part.
  • format is documentation, not enforcement, by default. A date string that is not a date passes unless the validator is switched into assertion mode.
  • additionalProperties must sit next to properties, not inside it. Nesting it is the single most common placement mistake in hand written schemas.
  • Drafts change meaning. exclusiveMinimum is a boolean on draft-07 and a number on draft 2020-12, and the same schema text validates differently on each.

What does JSON Schema validation actually check?

A JSON Schema is itself JSON. It is a document written in the same format as the data it judges, and its keys are a vocabulary with fixed meanings defined by the specification at json-schema.org. When a validator walks an instance, that is the name for the piece of data being judged, it applies each keyword it finds and combines the outcomes.

Three properties of that process explain nearly every surprise.

Keywords are independent. On the same object, every keyword that applies gets applied. There is no short-circuit from a passing keyword that protects a failing one. If an object passes type but fails required, it is invalid. If it passes required but fails pattern, it is invalid. The document is valid only when nothing on its path reports a failure. The one nuance: keywords that did not match, such as a properties branch for a key the instance does not have, simply skip.

instance /email /count /tags type: string pattern: ^..$ type: integer minimum: 0 items: string minItems: 1 keyword outcome verdict ok minItems fail valid iff all ok
Illustration of keyword independence on one object: each keyword runs on its own, and the verdict is valid only when nothing fails. Failures report per path, which is what validator error output lists.

A passing result is not a description of the data. Validation answers one question: does this instance satisfy the schema, yes or no. It assigns no meaning. A title and description in a schema never constrain anything; they are annotations, carried along for documentation because they happen to live beside the real keywords. The same is true of examples, default, and the pair of contentEncoding and contentMediaType, which describe how a string would be decoded rather than testing whether it was. That is also why format, covered below, behaves the way people least expect: it started as metadata about what type of string is assumed, and enforcement is an opt-in layer on top. Reading annotations as assertions is the single widest gap between what a schema looks like and what it does.

The basic keywords alone already catch the most expensive bugs. Type enforcement, required fields, bounds and string patterns catch wrong-type values, missing fields, malformed identifiers and out-of-range numbers. You rarely need conditional agonism to stop a broken document. You mostly need the boring keywords written correctly.

The keywords that reject documents

Let us take them in the order you will use them, with the behaviour each one actually has.

type, and the integer trap

type accepts seven values: string, number, integer, boolean, object, array and null. Two subtleties follow from how the specification defines them, and both are documented in the draft 2020-12 validation spec.

First, there is no type: "float" or type: "int". JSON itself, as standardised in RFC 8259, has one number type, and JSON Schema inherits it. Python or TypeScript style integer and float distinction does not exist in the data, only in what has a fractional part.

Second, integer is defined as a number whose fractional part is zero. The number 1.0 is a valid integer, because 1.0 and 1 are the same JSON value once parsed. If you need to reject 1.0, JSON Schema has no keyword that distinguishes lexical form, and you should decide whether you actually need to: a parser reading 1.0 into a float column will not mind. What integer does stop is 1.5 and "1", which is usually the real job.

A practical corollary: in the validation spec’s terms, number matches integers too. Setting "type": "number" on an age field lets 1.5 through; if half a person is not valid, say "type": "integer" and add a minimum.

required, properties and the shape of an object

properties maps names to subschemas. It applies to the matching keys of the object being judged, and it ignores everything else. required is a list of names that must exist. Three details bite in practice:

  • required only checks presence. A key whose value is null satisfies "required": ["email"]. If null is not acceptable, combine required with "type" under properties so both are checked.
  • An empty required list is legal and means “no requirement”. Generated schemas sometimes emit "required": [], which validates nothing and confuses readers.
  • A properties branch for a key the object does not have does not fire. That is why required exists separately: it is the keyword that makes a key mandatory rather than merely constrained.

To demand that a field both exist and have a given type, you need both keywords: "required": ["price"] at the object level and "price": { "type": "number" } inside properties.

enum and const: exactly equal, and what that means

enum lists the permitted values. const is shorthand for an enum with one entry. The specification defines its own notion of equality, and it is not the equality of your programming language.

Numbers compare numerically, so 1 and 1.0 are equal to an enum of [1]. Booleans and numbers are never equal, so true does not satisfy an enum of [1], unlike some JavaScript contexts where they treat as equal. Arrays and objects compare element by element and property by property.

The common bug is type drift upstream: a value that used to arrive as the number 1 now arrives as "1", the string. Your enum: [1, 2, 3] rejects it, which is correct. The visible symptom is an error naming enum on a value that looks like a member. When that error appears, check the type on the wire before touching the schema. Nothing here violates the data type rules covered in JSON data types explained.

pattern: regular expressions with no anchors

pattern applies to strings and uses the ECMA-262 regular expression dialect. Two consequences:

The pattern is unanchored by default. "pattern": "@\\w+" matches any string containing at-sign and word characters anywhere, including "junk@@example.com". If you mean the whole string, anchor it: "pattern": "^@\\w+$".

The dialect has no lookbehind in older engines and no (?<name>) group reuse tricks guaranteed across libraries, so keep patterns plain. A pattern that works in your editor can fail to compile in a Rust validator. Cross check anything ambitious with a small fixture before it ships.

format, covered in the mistakes section below, usually replaces a hand written pattern for dates, emails and URIs. patternProperties applies a pattern to key names, useful for dynamic keys like {"^cfg\\d+$": {...}}.

items and prefixItems: validating arrays

Two needs, two keywords. To say “every element is a string”:

{ "type": "array", "items": { "type": "string" } }

To say “the first element is a code, the second is a count” (a tuple):

{ "type": "array", "prefixItems": [ { "type": "string" }, { "type": "integer" } ] }

prefixItems positions subschemas by element position. Under draft 2020-12 items applies to any elements past the end of prefixItems, so the two compose cleanly. Under draft-07, the positional job was done by items as an array, with additionalItems handling the tail. If you are porting a schema forward, that is a real rewrite, not a rename.

A frequent assumption: that items forces a minimum length. It does not. [] validates happily against items: { "type": "string" }. Add minItems, and maxItems if there is one.

Numeric bounds, and the exclusive pair

minimum and maximum are inclusive; exclusiveMinimum and exclusiveMaximum exclude the bound itself. The classic breakage: under draft-07, exclusiveMinimum is a boolean that modifies minimum, { "minimum": 0, "exclusiveMinimum": true }. Under draft 2020-12 the keyword takes the number directly: { "exclusiveMinimum": 0 }. The draft 2020-12 release notes walk through this and other changes. A schema mixing both dialects is at best a silent annotation, at worst rejected by tools that read either version strictly.

Six mistakes that make schemas lie

These are ordered by how often they show up, and each one produces validation that is wrong in a specific direction.

1. additionalProperties inside properties. additionalProperties is a sibling of properties, a keyword on the object itself:

{ "type": "object",
  "properties": { "name": { "type": "string" } },
  "additionalProperties": false }

Nested under properties, the keyword does nothing: no key is named “additionalProperties”, so the branch never matches, and unknown keys sail through. The symptom is an API accepting fields you meant to forbid. The fix is structural. Also note the meaning: additionalProperties constrains keys not named in properties, so false on a typo, say "adress" instead of "address", produces “not allowed”, which is exactly the enforcement people usually want.

2. format as enforcement. The specification says format is an annotation by default. The validation spec describes it as a keyword that MAY be asserted, and modern validators describe their behaviour explicitly: the format documentation shows the difference. {"type": "string", "format": "date"} accepts "yesterday" unless the validator asserts formats. Half the ecosystem asserts by default and half does not, so a document lives or dies by which implementation received it. Decide deliberately. If you need the check carried by the schema itself, add a pattern or use a validator with format assertion enabled, and say so in your README.

3. integer and the 1.0 date. Covered above, but as a failure report: a pipeline stores counts as floats, your schema says type: "integer", and it passes, then a consumer writes the value into a database integer column and lands "2.0" in a text field. The schema did not fail. The mismatch is upstream. Validate types at your boundary with a strict tool such as the JSON Schema Validator, and the misbehaving source shows up immediately instead of in someone else’s ingestion job.

4. oneOf with overlapping branches. oneOf requires exactly one match among the listed subschemas. When two branches both allow the same document, it is invalid, and the error message from a naive validator is famously opaque, often “expected exactly one match” with no field names named. Two branches overlap when they share optional features, such as each branch making a different key optional. Prefer anyOf when overlapping is acceptable, or make branches distinguishable by shape, using additionalProperties: false so they cannot share. A oneOf error that makes no sense is almost always two branches sharing a shape.

5. required without type. "required": ["email"] accepts "email": null. Combine it with a properties entry and both checks run. This single pairing change removes most "email": null bugs people blame on their ORM.

6. Draft drift. Copy a schema from an old tutorial and it may be draft-07 or older, while your validator speaks 2020-12. Keywords with signatures that changed, like exclusiveMinimum, then mean different things. The section below gives you the map.

Where the specification came from, and why drafts matter

JSON Schema has never had a 1.0. It developed as IETF Internet-Drafts, and the versions were numbered until 2019, when the project started naming releases by the month of publication. The specification links page records every release date, and the arc explains a lot of ecosystem confusion.

2010 2013 2017 2018 2019 2022 draft-03 22 Nov 2010 draft-04 31 Jan 2013 draft-06 21 Apr 2017 draft-07 19 Mar 2018 2019-09 17 Sep 2019 2020-12 16 Jun 2022 JSON Schema releases, 2010 to 2022 Gap after draft-04: five years. That gap seeded today's dialect differences.
Source: JSON Schema specification links page, which records publication dates per draft.

That five year gap between draft-04 in 2013 and draft-06 in 2017 is why different tools learn different versions. The 2020-12 draft, named for its publication month, is the current one, and adoption of its semantics picked up sharply after February 2021, when the OpenAPI Initiative released OpenAPI 3.1.0 declaring 100 percent compatibility with draft 2020-12. Before that, OpenAPI documents used a modified subset, its own dialect, which is the politest word for a perennial source of tool bugs.

The 2020-12 draft brought concrete changes worth knowing when porting:

  • $defs replaces definitions as the standard place for named subschemas.
  • $ref no longer blocks sibling keywords. Under draft-07, a sibling keyword placed beside a $ref was ignored; under 2020-12, it applies.
  • unevaluatedProperties and unevaluatedItems generalize additionalProperties, which matters when composing schemas through allOf.
  • prefixItems replaces the tuple form of items.

The ecosystem has kept growing alongside it. The 2024 “State of JSON Schema” conference talk reported 48 implementations in the ecosystem in 2021 and 184 registered tools by late 2024, and measured the community growing over the same span from 6,174 members to over 18,000 people:

20k 15k 10k 5k 0 6,174 18,000+ 2021 late 2024 JSON Schema community members
Source: State of JSON Schema, JSON Schema Conference 2024 (December 2024).

validator libraries. The ecosystem now sees over 60 million weekly downloads, a figure the project displays on its homepage. Numbers at that scale mean a single keyword-level disagreement does not stay local: it propagates across every service that validates the same document with a different implementation.

How to read a validation error, when one appears

Errors read backwards from how you would expect, at first. A helpful error carries two locations: where in the data the failure sits, and which part of the schema blinked. They are usually not the same keyword.

Draft 2020-12 specifies a standardised output shape, the recommended output schema, with instanceLocation and keywordLocation fields, a pointer for each.

  • instanceLocation points into the document, for example /items/2/price, naming the price field of the third element.
  • keywordLocation points into the schema and says which keyword failed.

Paths are JSON Pointer style, which the handoff from validator to debugging session makes useful: you can paste the instance path into a viewer and walk straight to the offending value. Our own JSON Schema Validator reports both, plus line and column numbers in the document, so the step from error message to broken value is one click rather than one guess.

One habit separates quick fixes from long ones: if an error names a heading keyword such as allOf or oneOf, walk down the report rather than rewriting that applicator. Applicators compose subschemas, and the real failure is almost always one branch deep down, with its own instanceLocation.

The specification also defines how deep that report should go. Three output formats are named in the 2020-12 drafts: basic, a flat list of every individual check; detailed, which returns a tree of failures; and verbose, which additionally carries annotation output alongside them. Validators pick what to emit, so two tools over the same pair of documents can produce errors that look nothing alike while flagging the same mismatch. When comparing tools or writing a test that asserts on validator output, target instanceLocation and keywordLocation strings, which are stable across the formats, rather than the phrase a validator chose for its message. Tests failing over reworded English are a common reason teams disable validation, and asserting on the stable paths avoids it.

Putting validation into practice

Four habits turn this from theory into a routine you can rely on.

Create the schema from a sample. Hand writing a schema from memory invents structures the code does not send. Generate from a real response, and you get fewer empty required lists and fewer invented field names. The JSON Schema Generator does that from one document and lets you toggle optional constraints, generating draft 2020-12.

Then tighten deliberately. A generated schema is a starting outline. Decide, per field, whether null is a legal value, whether unknown fields are errors, whether every array has bounded length. That reframing from a data snapshot to a contract is where most value of validation lies, and it is five minutes’ thinking.

Test when the contract changes. Schemas change by hand editing between releases, and memory of what shifted is unreliable. When a schema changes, compare the old and new versions intentionally rather than trusting memory. JSON Schema Diff flags breaking changes: removed required fields, narrowed types, tightened patterns. Our OpenAPI helpers cover the related problem of turning schemas into OpenAPI documents and validating examples against them.

Validate at the boundary, once. Every service that receives external input should validate at the front door. Validate on each internal hop and you get slow checks for no additional information. Validate only at the very end and you find out about problems where the reporting is worst.

JSON Schema validation FAQ

Does validation check types beyond string, number, object and array? type recognizes seven values, adding boolean, integer and null to that list. But there is no separate float type, and integer matches any number with no fractional part. There is no way to distinguish 1 from 1.0 lexically.

Is format checked by default? No. format is documentation by default; it only rejects values when the validator is explicitly configured to assert formats. Check your implementation’s docs about the switch before relying on it. When you need a guarantee carried by the schema text, use pattern or patternProperties instead.

What is the difference between oneOf, anyOf and allOf? allOf requires every listed subschema to match. anyOf needs at least one. oneOf needs exactly one, which makes it the strictest and the one most likely to produce opaque errors on overlapping definitions. When in doubt about overlaps, use anyOf.

Why does my schema accept null for a required field? required checks presence only. To also reject null, add a properties entry with a type for the same field, so both presence and type are enforced together.

Which draft should I target? Draft 2020-12, unless a publishing tool forces otherwise. It is the current version, and OpenAPI 3.1, released in February 2021, aligns with it. When migrating from draft-07, the documented breaking changes are $defs, $ref siblings, prefixItems and the numeric exclusiveMinimum.

How do I check that generated JSON matches the schema exactly? That is precisely what validators do, and ours lays error paths per line and column inside the browser, without ever uploading your data. That is the same privacy model the whole site runs on: every tool, validation included, executes locally in your Web Worker.

The whole point of a schema

A schema is a contract made testable. The keywords are not bureaucracy; they are the words the contract is written in, and every one of them has a published meaning that does not budge between implementations that follow the specification. When validation surprises you, the explanation is nearly always one of the small independence rules above, not a mystery in the library. Reread the error, find the keyword, and the fix is usually a one line edit away.

If your documents are failing right now, bring the JSON and the schema and run them through the free online JSON Schema Validator. You get a document summary, per-error paths and line and column numbers, with nothing uploaded to any server, in line with how this site works.

Back to all posts