Validation and JSON Schema Basics
As JSON documents become more complex, JSON Schema provides a way to formally describe and validate their expected shape, catching structural mistakes before they cause problems downstream.
Why Validate JSON?
Just because a document is syntactically valid JSON doesn't mean it has the fields and types your application expects. Validation checks the actual structure and content — required fields, correct types, allowed value ranges — against a defined schema.
A Simple JSON Schema
JSON Schema is itself written in JSON, describing the expected shape of another JSON document.
{
"type": "object",
"properties": {
"name": { "type": "string" },
"price": { "type": "number", "minimum": 0 },
"inStock": { "type": "boolean" }
},
"required": ["name", "price"]
}
Common Mistakes
- Assuming syntactically valid JSON is automatically the correct shape your application expects — parsing success and structural correctness are two different concerns.
- Not marking essential fields as required in a schema, allowing incomplete data through unnoticed.
- Skipping validation entirely for data coming from external or third-party APIs, which can change unexpectedly.
- Writing overly rigid schemas that reject valid but slightly different data structures, such as additional optional fields.
Professional Tip
Validate JSON at the boundary of your system — right where external data enters, like an API response or a file upload — rather than scattering ad-hoc checks throughout your codebase. This keeps validation logic centralised and consistent.
Your Turn
Write a JSON Schema describing a valid 'user' object requiring a string username and a numeric age with a minimum of 0, then list two example JSON objects — one that would pass and one that would fail.
Mini Quiz
What is the main purpose of JSON Schema?