Skip to main content

A Practical JSON Schema Example You Can Copy and Adapt

Learn JSON Schema with a complete worked example: required fields, types, enums, formats, plus valid vs invalid data and how to validate JSON in Python and JavaScript.

👤 Tools Hub 📅 Jun 24, 2026 ⏱ 8 min read

A Practical JSON Schema Example You Can Copy and Adapt

A JSON Schema example is a small, declarative document that describes the shape of your JSON data: which fields are required, what types they hold, and what values are valid. In short, JSON Schema is a contract. You write the rules once, then validate any JSON payload against them automatically instead of writing brittle hand-rolled checks in code. This guide walks through a complete, working JSON schema example, explains every keyword in it, and shows you how to validate real data against it.

If you just want the direct answer: define an object with "type": "object", list your fields under "properties", mark must-have fields under "required", and add constraints like minLength, minimum, enum, or format to each property. Then run your data and your schema through a validator. To check your work in seconds, paste both into the free JSON Validator and fix any errors it reports.

What JSON Schema Actually Does

JSON Schema is a vocabulary written in JSON itself. Because the schema is just data, you can store it in your repository, version it, share it across teams, and feed it to validators in nearly every language: Python, JavaScript, Go, Java, and more. The most common reasons developers reach for it are validating API request and response bodies, checking configuration files before an app boots, and documenting a data contract so front end and back end agree on the same structure.

Without a schema, you typically end up scattering checks like "if this key is missing, throw an error" throughout your codebase. That logic drifts out of sync the moment requirements change. A schema centralizes those rules in one readable file, and the validator does the tedious work for you.

The keywords you will use most

  • type — the JSON type expected: string, number, integer, boolean, object, array, or null.
  • properties — a map of field names to their own sub-schemas.
  • required — an array of property names that must be present.
  • enum — restricts a value to a fixed list of allowed options.
  • minimum / maximum — numeric bounds.
  • minLength / maxLength / pattern — string length and regex constraints.
  • format — semantic hints such as email, uri, date-time, or uuid.
  • additionalProperties — whether unexpected fields are allowed.

A Complete Worked JSON Schema Example

Let us model a realistic object: a user profile sent to a sign-up endpoint. The data we want to validate looks like this.

{ "id": "9b2c...", "username": "ada_l", "email": "ada@example.com", "age": 36, "role": "admin", "tags": ["beta", "early-access"] }

Here is the JSON Schema example that describes and enforces that structure. Every constraint maps to a real rule a back end would want.

{ "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "User", "type": "object", "properties": { "id": { "type": "string", "format": "uuid" }, "username": { "type": "string", "minLength": 3, "maxLength": 20, "pattern": "^[a-z0-9_]+$" }, "email": { "type": "string", "format": "email" }, "age": { "type": "integer", "minimum": 13, "maximum": 120 }, "role": { "type": "string", "enum": ["admin", "editor", "viewer"] }, "tags": { "type": "array", "items": { "type": "string" }, "uniqueItems": true } }, "required": ["id", "username", "email", "role"], "additionalProperties": false }

Reading the schema line by line

The $schema key declares which JSON Schema draft you are targeting; using 2020-12 tells validators which keyword behaviors to apply. The title is documentation only. Under properties, each field gets its own rules: username must be 3 to 20 characters and match a lowercase-plus-digits-plus-underscore pattern, age must be an integer between 13 and 120, and role must be one of three allowed strings. The required array means id, username, email, and role must all appear, while age and tags are optional. Finally, "additionalProperties": false rejects any field not listed in properties, which is excellent for catching typos like "emial".

Valid vs. Invalid Data Side by Side

The fastest way to understand a schema is to see what it accepts and what it rejects. The table below runs three payloads against the schema above.

PayloadResultWhy
id, username "ada_l", valid email, role "admin"ValidAll required fields present and well typed.
username "Ada L" (space + uppercase)InvalidFails the pattern and contains a space.
role "superuser"InvalidNot in the enum list of allowed roles.
age "36" as a stringInvalidExpected integer, received string.
extra field "nickname"InvalidBlocked by additionalProperties: false.

Notice how each failure points to a specific, named rule. That precision is the whole value of schema validation: errors become actionable instead of vague. Before you trust a payload, it is worth pasting it into the JSON Validator to confirm it parses cleanly and matches expectations.

Validating JSON Against the Schema in Code

A schema is only useful when something checks data against it. Most languages have a mature validator library. Here is a minimal Python example using the widely used jsonschema package.

import json from jsonschema import validate, ValidationError with open("user.schema.json") as f: schema = json.load(f) data = {"id": "9b2c4f10-...", "username": "ada_l", "email": "ada@example.com", "role": "admin"} try: validate(instance=data, schema=schema) print("Valid: data matches the schema") except ValidationError as err: print("Invalid:", err.message) print("At path:", list(err.absolute_path))

The same idea applies in JavaScript with ajv, the most popular Node validator. Compile once and reuse the validator function for speed.

import Ajv from "ajv"; import addFormats from "ajv-formats"; const ajv = new Ajv({ allErrors: true }); addFormats(ajv); const validate = ajv.compile(schema); const ok = validate(data); if (!ok) console.log(validate.errors);

Common pitfalls when writing your first schema

  • Forgetting required. Listing a property under properties does not make it mandatory. Optional and required are separate concepts.
  • Leaving additionalProperties open. By default extra fields are allowed, so typos slip through unless you set it to false.
  • Confusing number and integer. 42.0 is a valid number but not always a valid integer depending on the draft.
  • Assuming format is always enforced. Some validators treat format as annotation only unless you enable format checking explicitly, as with ajv-formats above.

Building Your Schema Incrementally

You do not have to write the whole schema at once. A reliable workflow is to start from a real sample of your data, then tighten the rules over a few passes.

  1. Grab one representative JSON object that you know is correct.
  2. Write a loose schema: just type: object and properties with their types.
  3. Validate the sample. Once it passes, add required for fields that must always exist.
  4. Layer in constraints (enum, minLength, minimum) one at a time, re-validating after each addition.
  5. Finally set additionalProperties: false and run a few deliberately broken payloads to confirm the schema rejects them.

Re-validating after every change is the key habit. If you are iterating quickly, keep the JSON Validator open in another tab so you can paste, check, and adjust without setting up a local environment. For more tools in the same family, browse the development tools hub.

A good schema is strict enough to catch real mistakes but loose enough that valid, evolving data still passes. Start permissive and tighten gradually.

Where JSON Schema Fits Alongside Other Tasks

Schema validation often sits next to other everyday data chores. If your schema uses "format": "uuid", you may need to generate identifiers for tests; our guide to generating UUIDs in Python pairs well with the id field above. The pattern keyword expects a regular expression, so a quick refresher with the regex cheat sheet helps you write correct constraints the first time. And when two payloads should match a schema but behave differently, a structural JSON compare reveals exactly which keys diverged.

Frequently Asked Questions

What is a JSON Schema example in simple terms?

It is a JSON document that describes another JSON document. It declares the expected fields, their types, and validity rules so a validator can automatically confirm whether real data conforms, instead of you writing manual checks.

Which JSON Schema draft should I use?

For new projects, use draft 2020-12, the most current and widely supported version. Declare it with the $schema keyword. Older drafts like draft-07 are still common in existing tooling, so match whatever your validator library supports.

How do I make a field required in JSON Schema?

Add the field name to the required array at the same level as properties. Defining a property under properties alone does not make it mandatory; the two are intentionally separate.

How do I block unexpected fields?

Set "additionalProperties": false on the object. The validator will then reject any property not explicitly listed under properties, which is the simplest way to catch typos and stray keys.

Does JSON Schema validate email and date formats?

It can, through the format keyword with values like email, date-time, or uuid. However, some validators treat format as an annotation by default. Enable format assertion explicitly, for example by adding ajv-formats in JavaScript.

Can I validate JSON against a schema online without installing anything?

Yes. Paste your JSON into the browser-based JSON Validator to confirm it is syntactically valid and well structured. It runs entirely in your browser with no signup, which is ideal for quick checks while you iterate on a schema.

What is the difference between number and integer types?

integer accepts whole numbers only, while number accepts both integers and decimals. Use integer for counts, ages, and IDs, and number for prices or measurements that may have fractional parts.

Tools Hub
Free online tools, every day

Share on Social Media:

ads

Please disable your ad blocker!

We understand that ads can be annoying, but please bear with us. We rely on advertisements to keep our website online. Could you please consider whitelisting our website? Thank you!