JSON Validation Guide
1. Basic JSON Validation
Syntax Validation
Basic JSON syntax validation checks for:
- Proper opening and closing brackets
- Valid key-value pairs
- Correct use of commas and colons
- Proper string escaping
Example Valid JSON
{
"name": "John Doe",
"age": 30,
"isStudent": false
}
Example Invalid JSON
{
"name": "John Doe",
"age": 30,
"isStudent": false, // Trailing comma
}
2. JSON Schema Validation
Schema Example
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"age": {
"type": "integer",
"minimum": 0
},
"email": {
"type": "string",
"format": "email"
}
},
"required": ["name", "age"]
}
Validating Against Schema
const Ajv = require('ajv');
const ajv = new Ajv();
const schema = {
// ... schema definition
};
const validate = ajv.compile(schema);
const valid = validate(data);
if (!valid) {
console.log(validate.errors);
}
3. Common Validation Scenarios
Type Validation
{
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "number" },
"isActive": { "type": "boolean" },
"tags": { "type": "array" }
}
}
Format Validation
{
"type": "object",
"properties": {
"email": { "format": "email" },
"date": { "format": "date" },
"url": { "format": "uri" },
"uuid": { "format": "uuid" }
}
}
4. Validation Tools
Online Validators
- JSONLint
- JSON Schema Validator
- JSON Formatter & Validator
Library Options
- Ajv (JavaScript)
- jsonschema (Python)
- json-schema-validator (Java)
5. Best Practices
Validation Guidelines
- Always validate input data
- Use JSON Schema for complex validation
- Implement proper error handling
- Validate data at multiple levels
- Keep validation rules up to date
Error Handling
{
"status": "error",
"code": "VALIDATION_ERROR",
"message": "Invalid input data",
"errors": [
{
"field": "email",
"message": "Invalid email format"
},
{
"field": "age",
"message": "Age must be a positive number"
}
]
}