Popular JSON Schema Validators
JSON Schema validators are essential tools for validating JSON data against a defined schema. They help ensure that the data structure adheres to the expected format, which is crucial for data integrity and application stability. Below are some popular JSON Schema validators along with sample code for each.
1. AJV (Another JSON Schema Validator)
AJV is a fast and efficient JSON Schema validator for JavaScript. It compiles schemas into functions for quick validation.
const Ajv = require("ajv");
const ajv = new Ajv();
const schema = {
type: "object",
properties: {
temperature: { type: "number" },
unit: { type: "string" },
temperatureOf: { type: "string" },
},
required: ["temperature", "unit"],
additionalProperties: false,
};
const validate = ajv.compile(schema);
const data = {
temperature: 15.7,
unit: "Celsius",
temperatureOf: "weather",
};
const valid = validate(data);
if (valid) {
console.log("JSON Schema is valid");
} else {
console.log("JSON Schema is invalid");
console.log(validate.errors);
}
2. jsonschema (Python)
The jsonschema library is a popular choice for validating JSON data in Python. It follows the JSON Schema specification closely.
from jsonschema import validate
schema = {
"type": "object",
"properties": {
"temperature": {"type": "number"},
"unit": {"type": "string"},
"temperatureOf": {"type": "string"},
},
"required": ["temperature", "unit"],
"additionalProperties": False,
}
data = {
"temperature": 15.7,
"unit": "Celsius",
"temperatureOf": 34,
}
validate(instance=data, schema=schema)
3. gojsonschema (Go)
gojsonschema is a Go library for validating JSON data against JSON Schema. It is easy to use and integrates well with Go applications.
package main
import (
"github.com/xeipuuv/gojsonschema"
"log"
)
func main() {
schemaLoader := gojsonschema.NewReferenceLoader("file:///path/to/schema.json")
documentLoader := gojsonschema.NewStringLoader(`{"temperature": 15.7, "unit": "Celsius", "temperatureOf": "weather"}`)
result, err := gojsonschema.Validate(schemaLoader, documentLoader)
if err != nil {
log.Fatal(err)
}
if result.IsValid() {
log.Println("The JSON data is valid")
} else {
log.Println("The JSON data is not valid. Errors:")
for _, err := range result.Errors() {
log.Printf("- %s\n", err)
}
}
}
4. jsonschema-rs (Rust)
jsonschema-rs is a Rust library for validating JSON data against JSON Schema. It is designed for performance and safety.
use jsonschema::{JSONSchema, Schema};
fn main() {
let schema = Schema::compile(&serde_json::from_str(r#"
{
"type": "object",
"properties": {
"temperature": { "type": "number" },
"unit": { "type": "string" },
"temperatureOf": { "type": "string" }
},
"required": ["temperature", "unit"],
"additionalProperties": false
}
"#).unwrap()).unwrap();
let data = serde_json::from_str(r#"
{
"temperature": 15.7,
"unit": "Celsius",
"temperatureOf": "weather"
}
"#).unwrap();
let validation = schema.validate(&data);
match validation {
Ok(_) => println!("JSON Schema is valid"),
Err(errors) => println!("JSON Schema is invalid: {:?}", errors),
}
}
5. Conclusion
These validators are widely used in various programming languages and provide robust solutions for validating JSON data against schemas. Choosing the right validator depends on your specific use case and the programming language you are using.