Schema Validation
Validate your JSON with JSON Schema. Learn how to define, apply, and test schemas for robust, error-free data.
Why Use JSON Schema?
- Data Validation: Ensure your JSON data meets specific requirements
- Documentation: Self-documenting data structures
- Code Generation: Generate code, forms, and documentation from schemas
- API Design: Define clear contracts for API requests and responses
Basic Schema Structure
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"age": {
"type": "integer",
"minimum": 0
}
},
"required": ["name", "age"]
}
Common Validation Keywords
type: Defines the data type (string, number, object, array, boolean, null)required: Specifies which properties are mandatoryproperties: Defines the properties of an objectitems: Defines the schema for array itemsminimum/maximum: Sets numeric value limitsminLength/maxLength: Sets string length limitspattern: Defines a regular expression patternenum: Lists allowed valuesformat: Specifies data format (email, date-time, uri, etc.)
Example: User Profile Schema
Let's look at a more complex example that validates a user profile:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["id", "username", "email"],
"properties": {
"id": {
"type": "string",
"pattern": "^usr_[a-zA-Z0-9]{8}$"
},
"username": {
"type": "string",
"minLength": 3,
"maxLength": 30
},
"email": {
"type": "string",
"format": "email"
}
}
}
Validation Tools
Several tools can help you validate JSON against schemas:
- JSON Schema Validator - Online validator
- Ajv - JavaScript validator
- JsonSchema Validator - Java validator
- jsonschema - Python validator
Best Practices
- Always specify the
$schemaversion - Use descriptive property names
- Include helpful error messages in descriptions
- Validate early in your application pipeline
- Keep schemas modular and reusable
- Use references to avoid schema duplication
Try It Yourself
Check out our example files: