What Is a JSON Schema, and How Do You Validate Against One?
A JSON schema is a contract that describes the expected shape of a JSON document, which fields exist, their types, and which ones are required, rather than the data itself. Two wildly different JSON documents can both be valid against the same schema, as long as they both follow the shape it describes.
Why you'd bother
Validating against a schema catches a malformed API response, a broken config file, or bad data in a pipeline before it causes a confusing failure three steps further downstream, where the actual cause is much harder to trace back to. It's the same idea as a database column constraint, applied to a document instead of a table row.
What a basic schema looks like
A schema for a simple user record might look like this:
{
"type": "object",
"properties": {
"email": { "type": "string" },
"age": { "type": "number" },
"active": { "type": "boolean" }
},
"required": ["email"]
}That says: the document must be an object; if it has an emailfield it must be a string, if it has age it must be a number; and email specifically must be present, everything else on this list is optional. A document missing email, or one where age is the string "25" instead of the number 25, fails validation against it.
Reading a validation error
A validator reports errors by path and reason, not just "invalid." The three you'll hit most often:
- Required property missing — a field the schema marks required doesn't appear in the document at all.
- Type mismatch — a field is present but the wrong kind of value, a string where a number was expected, most commonly.
- Additional property not allowed — the document has a field the schema doesn't list, and the schema was written to reject anything extra rather than silently ignore it.
Validating with Kit-Bin's tool
JSON Schema Validator checks a JSON document against a schema entirely in your browser, and supports both the 2020-12 and draft-07 schema drafts, selectable before you run it, since older API and OpenAPI projects commonly still use draft-07. It deliberately doesn't follow remote $ref links, so paste every schema a document references directly into the schema box rather than pointing at a URL.
Have a JSON syntax problem rather than a schema mismatch, stray commas, unquoted keys? That's a different, more basic failure than schema validation. See JSON Diff to compare two versions of a document directly instead.