All articles

JSON Schema: describing and validating JSON structure

JSON Schema is a way to describe what the structure of a JSON document should look like, using another JSON document. Instead of validating data by hand with conditionals in code, you can declaratively describe the expected types, required fields, and value constraints, then check data against that description automatically.

Core draft-07 keywords

  • type — the expected value type (object, string, number, array, and so on).
  • required — a list of object fields that must be present.
  • properties — the schema for each individual field of an object.
  • enum — restricts a value to a specific set of allowed options.
  • pattern — validates a string against a regular expression, e.g. for a postal code format.

One "postal code" pattern doesn't cover the English-speaking world

A schema for a UK address needs a very different pattern than one for a US address: US ZIP codes are simple five digits (^\d{5}$), but a UK postcode is alphanumeric and irregular in length — SW1A 1AA, M1 1AE, B33 8TH are all valid, and the official regex has several alternative shapes chained together. A contract-testing schema written against one country's sample data and shipped as "the address schema" will reject perfectly valid addresses from the other the moment it's reused — a common gotcha when an API serves multiple English-speaking markets.

How this differs from syntax validation

Plain JSON validation only checks that the text is syntactically correct — matching brackets, quotes, commas. JSON Schema checks a lot more: whether an object has a required email field, whether age is a number rather than a string, whether status is one of the allowed values.

Why you need this

  • Verify that a third-party API's response matches its documented contract.
  • Validate config files before deployment to catch a mistake early.
  • Document the expected data structure in a format that can be checked automatically right away.

additionalProperties: can extra fields be added

By default, JSON Schema allows an object to contain any fields beyond the ones described in propertiesrequired and properties only set a minimum, not an exhaustive list. To forbid unknown fields, you need to explicitly add "additionalProperties": false — without that flag, the schema stays "open".

Try the tool