Schema validation for JSON: validating shape, not just syntax
Valid JSON isn't correct JSON. Learn to use JSON Schema to validate the expected shape at the API boundary, in configs, and in contracts between services.
The API accepted the payload, returned 200, and three services downstream broke. The reason: the front end sent "42" (a string) where the contract said 42 (a number), and nobody checked. The JSON was syntactically perfect — braces closed, commas in place, quotes correct — and still wrong. That gap, between "this is valid JSON" and "this is the JSON I expected", is exactly the hole schema validation exists to plug.
This guide covers the difference between validating syntax and validating shape, what JSON Schema is, where to apply validation, and why one shared schema beats ten defensive ifs scattered across the codebase.
Valid syntax is not the same as correct shape
Validating syntax answers one question: "is this parseable JSON?". Any JSON.parse does that and blows up if you forgot a comma. But it happily accepts an object with the wrong field, a number where text belonged, or a missing email — because syntactically everything is fine.
Schema validation answers a different, more useful question: "does this JSON have the shape my system expects?". Are the right fields present? Do the types match? Is status one of the allowed values? That's the check that separates data that merely looks right from data that actually is.
What JSON Schema is
JSON Schema is a standard (itself written in JSON) for declaring the expected shape of a document. You describe types, required fields, allowed values, formats, and bounds, then validate any payload against that description.
{
"type": "object",
"required": ["id", "email", "status"],
"properties": {
"id": { "type": "integer", "minimum": 1 },
"email": { "type": "string", "format": "email" },
"status": { "type": "string", "enum": ["active", "inactive"] },
"tags": { "type": "array", "items": { "type": "string" } }
},
"additionalProperties": false
}
This schema rejects the payload from the top of the article immediately:
{ "id": "42", "email": "joe@", "status": "on" }
Three errors at once: id is a string, not an integer; email has no valid format; and status isn't in the enum. Better still, the validator points to where each one failed, instead of a generic "invalid data".
Validate at the boundary, always
The rule is simple: all data from outside is untrusted until validated, and validation happens at the boundary — at the entry point, before any business logic. That applies to:
- API input — validate the request body against the schema before processing. Fail with a
400and a clear error, not a stack trace three layers down. - Configuration files — a schema for your
config.jsoncatches the typo in a key name at startup, not in production at 2 a.m. - Contracts between services — service A produces, service B consumes, and both validate against the same schema. Nobody has to guess the other's format.
To check a payload against a schema without deploying anything, the JSON Schema validator does it right in the browser and shows the exact path of each error — handy when all you want is to confirm a contract before coding against it.
Tooling: you don't write the validator
Nobody implements schema validation by hand. Every language has a mature library: Ajv in JavaScript/TypeScript (fast, compiles the schema), jsonschema in Python, and equivalents in nearly every ecosystem. They implement the spec, so the same schema works on either side of the contract.
import Ajv from "ajv";
import addFormats from "ajv-formats";
const ajv = addFormats(new Ajv({ allErrors: true }));
const validate = ajv.compile(schema);
if (!validate(payload)) {
// each error carries instancePath + message — return that, not a 500
console.log(validate.errors);
}
Note allErrors: true: by default many validators stop at the first error. Turning it on returns the full list at once, which is far better for whoever's on the other side trying to fix the request.
Generating the schema from an example
Writing the first schema by hand is tedious. An honest shortcut: take a real sample payload, generate the initial schema from it with an inference tool, then tighten it — sharpen the enums, mark the required fields, swap a generic string for format: "email". It's much faster than starting from scratch, and it forces you to look field by field, which is exactly the point. If you're still on the previous step — making sure the JSON even parses — it's worth reading how to validate JSON and the most common syntax errors first.
Frequently asked questions
What's the difference between validating JSON and validating with a schema?
Validating JSON checks syntax: whether the text parses (commas, quotes, braces). Validating with a schema checks shape: whether fields, types, and values match what's expected. JSON can pass the first and fail the second — the classic case of the number that arrived as a string. You want both, in that order.
Where should I put schema validation?
At the system boundary, before business logic: API input, config loading, and on both sides of a contract between services. The idea is to fail fast with a clear error (path + reason) instead of letting malformed data leak inward and break three layers later.
Do I need to write the validator myself?
No, and you shouldn't. Use libraries that implement the spec — Ajv in JS, jsonschema in Python, and equivalents. They cover the edge cases of the spec you don't want to reimplement, and the same schema runs identically across all of them, which is the whole point of a standard.
Does JSON Schema replace business-rule validation?
No. Schema validates structure (types, requiredness, format, ranges) — "is this field a well-formed email?". Business rules are something else — "is this email already registered?" requires hitting the database. Use schema for shape and keep domain rules in separate code.
What to take from this guide
Valid JSON is not correct JSON. Syntax guarantees the text parses; the schema guarantees it has the shape your system expects. Declare that shape once with JSON Schema, validate all outside data at the boundary, and share the same schema between producer and consumer. Use an off-the-shelf library, turn on allErrors, and return the error with its path and reason. That's the difference between catching the problem at the 400 on the way in and hunting it down in a 500 three services later.
- 01 Does the PageSpeed Score Affect SEO? 100/100 and Failing Google doesn't rank on PageSpeed's 0 to 100 score but on Core Web Vitals from real users. Here's why a site scores 100/100 and still fails in the field.
- 02 Unit test vs integration test: the difference in practice The difference between unit and integration tests with API and database examples: what each one catches, what it costs, and when to use each in your project.