Introduction
JSON Schema provides a way to describe and validate JSON data structures. It’s essential for API development to ensure data integrity and provide clear error messages.
What is JSON Schema?
JSON Schema is a vocabulary that allows you to annotate and validate JSON documents. It’s like TypeScript types but for runtime validation.
Basic Schema
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "number",
"minimum": 0,
"maximum": 150
},
"email": {
"type": "string",
"format": "email"
}
},
"required": ["name", "email"]
}
Validation Example
Validating User Input
import Ajv from "ajv";
const schema = {
type: "object",
properties: {
name: { type: "string", minLength: 1 },
email: { type: "string", format: "email" },
age: { type: "integer", minimum: 0 },
},
required: ["name", "email"],
};
const ajv = new Ajv();
const validate = ajv.compile(schema);
const data = {
name: "Alice",
email: "alice@example.com",
age: 30,
};
const valid = validate(data);
if (!valid) {
console.error(validate.errors);
}
Tools
Use our tools:
- JSON Schema Validator - Validate JSON against schemas
Conclusion
JSON Schema validation ensures:
Benefits:
- Data integrity
- Clear error messages
- API documentation
- Type safety at runtime
Next Steps
- Validate with JSON Schema Validator
- Learn API Best Practices
- Explore Schema Design