| Crates.io | json-schema-validator-core |
| lib.rs | json-schema-validator-core |
| version | 1.0.0 |
| created_at | 2025-09-20 08:05:18.435025+00 |
| updated_at | 2025-09-20 08:05:18.435025+00 |
| description | Lightning-fast JSON schema validation library with custom error messages and multi-language bindings |
| homepage | |
| repository | https://github.com/rust-core-libs/json-schema-validator-core |
| max_upload_size | |
| id | 1847509 |
| size | 102,871 |
A lightning-fast JSON Schema validation library written in Rust with comprehensive error reporting and multi-language bindings support. Designed for high-performance applications requiring strict JSON validation with detailed, actionable error messages.
Add this to your Cargo.toml:
[dependencies]
json-schema-validator-core = "1.0.0"
Basic example:
use json_schema_validator_core::{JsonSchemaValidator, ValidationOptions};
use serde_json::json;
fn main() {
let schema = json!({
"type": "object",
"properties": {
"name": {"type": "string", "minLength": 1},
"age": {"type": "integer", "minimum": 0, "maximum": 150},
"email": {"type": "string", "format": "email"}
},
"required": ["name", "age"]
});
let instance = json!({
"name": "John Doe",
"age": 30,
"email": "john@example.com"
});
let options = ValidationOptions::default();
let validator = JsonSchemaValidator::new(schema, options).unwrap();
if validator.is_valid(&instance) {
println!("✅ Valid JSON!");
} else {
let errors = validator.validate(&instance);
for error in errors {
println!("❌ {}: {}", error.instance_path, error.message);
}
}
}
use json_schema_validator_core::{JsonSchemaValidator, ValidationOptions, SchemaDraft};
use std::collections::HashMap;
let mut custom_formats = HashMap::new();
custom_formats.insert("phone".to_string(), |s: &str| -> bool {
s.len() >= 10 && s.chars().all(|c| c.is_ascii_digit() || c == '-' || c == ' ')
});
let options = ValidationOptions {
draft: SchemaDraft::Draft7,
custom_formats,
short_circuit: false, // Collect all errors
collect_annotations: true,
..Default::default()
};
let schema = json!({
"type": "object",
"properties": {
"phone": {"type": "string", "format": "phone"}
}
});
let validator = JsonSchemaValidator::new(schema, options).unwrap();
Build the shared library:
cargo build --release
Use in C/C++:
#include <stdio.h>
#include <stdlib.h>
extern char* validate_json_simple(const char* schema_json, const char* instance_json);
extern void free_string(char* ptr);
int main() {
const char* schema = "{\"type\": \"string\", \"minLength\": 3}";
const char* instance = "\"hi\"";
char* errors = validate_json_simple(schema, instance);
if (errors) {
printf("Validation errors: %s\n", errors);
free_string(errors);
}
return 0;
}
import init, { wasm_validate_json, wasm_is_valid } from './pkg/json_schema_validator_core.js';
async function validateJson() {
await init();
const schema = JSON.stringify({
type: "object",
properties: {
name: { type: "string" },
age: { type: "integer", minimum: 0 }
},
required: ["name"]
});
const instance = JSON.stringify({ name: "Alice", age: 25 });
const isValid = wasm_is_valid(schema, instance);
console.log("Is valid:", isValid);
if (!isValid) {
const errors = JSON.parse(wasm_validate_json(schema, instance));
console.log("Errors:", errors);
}
}
null, boolean, integer, number, string, array, object{"type": ["string", "null"]}minLength / maxLength - Length constraintspattern - Regular expression matchingformat - Built-in format validation (email, uri, date, datetime, ipv4, ipv6, uuid)minimum / maximum - Value constraintsexclusiveMinimum / exclusiveMaximum - Exclusive boundsmultipleOf - Divisibility constraintsminItems / maxItems - Length constraintsuniqueItems - Uniqueness enforcementitems - Item schema validationadditionalItems - Additional item handlingminProperties / maxProperties - Property count constraintsrequired - Required property enforcementproperties - Property schema validationadditionalProperties - Additional property handlingpatternProperties - Pattern-based property validationenum - Enumeration validationconst - Constant value validationallOf / anyOf / oneOf - Schema compositionnot - Schema negationEach validation error provides detailed context:
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationError {
pub instance_path: String, // JSONPointer to the invalid data
pub schema_path: String, // JSONPointer to the failing schema
pub keyword: String, // The failing keyword (e.g., "minLength")
pub message: String, // Human-readable error message
pub instance_value: Option<Value>, // The invalid value
pub schema_value: Option<Value>, // The schema constraint
}
Example error output:
[
{
"instance_path": "/user/age",
"schema_path": "/properties/user/properties/age/minimum",
"keyword": "minimum",
"message": "Value -5 is less than minimum 0",
"instance_value": -5,
"schema_value": 0
}
]
Optimized for high-throughput applications:
Benchmark results on a modern CPU:
| Feature | Draft 4 | Draft 6 | Draft 7 | 2019-09 | 2020-12 |
|---|---|---|---|---|---|
| Core Keywords | ✅ | ✅ | ✅ | ✅ | ✅ |
| Format Validation | ✅ | ✅ | ✅ | ✅ | ✅ |
| Schema Composition | ✅ | ✅ | ✅ | ✅ | ✅ |
| Conditional Schemas | ❌ | ❌ | ✅ | ✅ | ✅ |
| Annotations | ❌ | ❌ | ✅ | ✅ | ✅ |
All exports are designed with safety in mind:
git clone https://github.com/rust-core-libs/json-schema-validator-core.git
cd json-schema-validator-core
cargo build
cargo build --release
wasm-pack build --target web
cargo test
cargo bench
cargo doc --open
Perfect for:
use json_schema_validator_core::{JsonSchemaValidator, ValidationOptions};
// Define API schema
let user_schema = json!({
"type": "object",
"properties": {
"id": {"type": "integer", "minimum": 1},
"username": {
"type": "string",
"minLength": 3,
"maxLength": 20,
"pattern": "^[a-zA-Z0-9_]+$"
},
"email": {"type": "string", "format": "email"},
"profile": {
"type": "object",
"properties": {
"firstName": {"type": "string", "minLength": 1},
"lastName": {"type": "string", "minLength": 1},
"age": {"type": "integer", "minimum": 13, "maximum": 120}
},
"required": ["firstName", "lastName"]
}
},
"required": ["username", "email"],
"additionalProperties": false
});
let validator = JsonSchemaValidator::new(user_schema, ValidationOptions::default()).unwrap();
// Validate incoming requests
fn validate_user_request(data: &str) -> Result<(), Vec<ValidationError>> {
let instance: Value = serde_json::from_str(data)?;
let errors = validator.validate(&instance);
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
// Database configuration schema
let config_schema = json!({
"type": "object",
"properties": {
"database": {
"type": "object",
"properties": {
"host": {"type": "string", "format": "hostname"},
"port": {"type": "integer", "minimum": 1, "maximum": 65535},
"username": {"type": "string", "minLength": 1},
"password": {"type": "string", "minLength": 8},
"ssl": {"type": "boolean"}
},
"required": ["host", "port", "username", "password"]
},
"logging": {
"type": "object",
"properties": {
"level": {"enum": ["error", "warn", "info", "debug", "trace"]},
"format": {"enum": ["json", "text"]}
}
}
},
"required": ["database"]
});
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
git checkout -b feature/amazing-feature)cargo test)cargo bench)git commit -am 'Add amazing feature')git push origin feature/amazing-feature)cargo fmt before committingcargo clippy and fix any warningsThis project is licensed under either of
at your option.
Built with Rust 🦀 for speed and safety.