How to Use JSON Schema to Validate Your Data
What is a JSON Schema?
A JSON Schema is a standardized way to describe the structure, required fields, and value types in your JSON data. Think of it as a contract or blueprint for what valid JSON should look like. JSON Schema is written in JSON itself, making it both machine-readable and easy to edit.
Why Validate with a Schema?
- Prevent bugs by catching invalid or missing data before it causes problems.
- Enforce data consistency across different teams, apps, or APIs.
- Generate documentation automatically from schemas.
- Help editors and tools provide better auto-completion and inline help.
A Simple Example: Basic Schema
Here's a basic JSON object, followed by a minimal schema that validates its structure:
{
"name": "Alice",
"age": 30
}
{
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "number" }
},
"required": ["name", "age"]
}
This schema ensures that the object must have a 'name' (as a string) and an 'age' (as a number).
How to Write a Custom Schema
You can define advanced rules in your schema: restrict field values, define nested objects, or set minimum/maximum numbers. Here’s an example that validates an array of products:
{
"type": "array",
"items": {
"type": "object",
"properties": {
"id": { "type": "string" },
"price": { "type": "number", "minimum": 0 },
"tags": {
"type": "array",
"items": { "type": "string" }
}
},
"required": ["id", "price"]
}
}
Using JSONValidator.dev for Schema Validation
- Paste your JSON data in the main editor.
- Paste your JSON Schema in the schema editor below.
- Click Validate JSON Against This Schema.
- Review validation results, with any errors highlighted and explained.
Troubleshooting Schema Validation Errors
Common reasons for validation errors include:
- A required field is missing from your data.
- A value type does not match the schema (e.g., string vs. number).
- The schema itself is invalid or contains typos.
Conclusion
JSON Schema validation is a powerful way to make your data robust and error-proof. Try creating a schema for your own data with our free JSON Schema Generator and validate it live!