If you're a developer working with APIs, configuration files, or data storage, you deal with JSON every day. But how do you know if the JSON data you're receiving is correctly structured? That's where JSON Schema comes in.
What is JSON Schema?
JSON Schema is a vocabulary that allows you to annotate and validate JSON documents. It acts as a contract for your data. Just like strongly typed languages ensure variables are the correct type, JSON Schema ensures your JSON objects have the right keys, the correct value types, and follow specific formatting rules.
A simple JSON Schema looks like this:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "number", "minimum": 0 },
"email": { "type": "string", "format": "email" }
},
"required": ["name", "email"]
}
Why is Validation Important?
Without validation, your application might try to access user.age.toFixed() when age was accidentally sent as a string (or wasn't sent at all). This leads to runtime crashes, security vulnerabilities, and bad user experiences.
How to Validate JSON using Ajv
Ajv (Another JSON Schema Validator) is the industry standard engine for validating JSON against a schema. It is extremely fast and fully supports the latest drafts of the JSON Schema specification.
To validate your JSON quickly without setting up a Node.js project, you can use a free online tool like JSON OS Validator. It runs Ajv completely in your browser.
- Open the JSON OS Validator.
- Paste your JSON document in the main editor.
- Press
Cmd + \to open the side panel, select the Schema tab, and paste your JSON Schema.
If there are any errors (like a missing "email" or a negative "age"), the editor will highlight the exact line and column where the error occurred, along with the specific instancePath.
Conclusion
Using JSON Schema guarantees that your data is predictable. Next time you're building an API or a config file, draft a schema and validate it instantly using local-first tools like JSON OS.