json-eval-rs
High-performance JSON Logic evaluation library with schema validation and multi-platform bindings
json-eval-rs is a blazing-fast JSON Logic evaluator written in Rust, featuring a custom-built compiler, intelligent caching, parallel evaluation, and comprehensive schema validation. It provides seamless integration across multiple platforms through native bindings.
âĻ Key Features
- ð High Performance: Custom JSON Logic compiler with pre-compilation and zero-copy caching
- ð Parallel Evaluation: Multi-threaded processing with dependency-aware topological sorting
- ð Schema Validation: Built-in validation with detailed error reporting
- ð Multi-Platform: Native bindings for Rust, C#/.NET, Web (WASM), and React Native
- ðū Smart Caching: Content-based caching with Arc-based zero-copy storage
- ð Dependency Tracking: Automatic field dependency detection for selective re-evaluation
- ð SIMD Optimized: Uses
simd-jsonfor ultra-fast JSON parsing
ðŊ Use Cases
- Dynamic Form Validation: Real-time validation with complex business rules
- Configuration Management: Evaluate dynamic configurations with dependencies
- Business Rule Engines: Execute complex business logic with high performance
- Data Transformation: Transform and validate large datasets efficiently
- UI Layout Resolution: Resolve conditional layouts with
$refreferences
ð Documentation
ð Comprehensive Operator Documentation - Complete guide to all 80+ available operators:
- Quick Reference - Alphabetical operator list
- Core Operators - Variables and literals
- Logical Operators - Boolean logic (
and,or,if, etc.) - Comparison Operators - Value comparisons (
==,<,>, etc.) - Arithmetic Operators - Math operations (
+,-,*,/, etc.) - String Operators - Text manipulation (
cat,substr,search, etc.) - Math Functions - Advanced math (
round,abs,max, etc.) - Date Functions - Date/time operations (
today,dateformat, etc.) - Array Operators - Array transformations (
map,filter,reduce, etc.) - Table Operators - Data lookups (
VALUEAT,INDEXAT, etc.) - Utility Operators - Helper functions (
missing,RANGEOPTIONS, etc.)
ðĶ Installation
Rust
[]
= "0.0.29"
C# / .NET
Web / JavaScript / TypeScript
React Native
ð Quick Start
Rust
use JSONEval;
C#
using JsonEvalRs;
var schema = @"{
""type"": ""object"",
""properties"": {
""age"": {
""rules"": {
""minValue"": { ""value"": 18, ""message"": ""Must be 18 or older"" }
}
}
}
}";
using (var eval = new JSONEval(schema))
{
var data = @"{""age"": 25}";
var result = eval.Evaluate(data);
var validation = eval.Validate(data);
if (!validation.HasError)
{
Console.WriteLine("â
Data is valid!");
}
}
Web (TypeScript)
import { JSONEval } from '@json-eval-rs/web';
const schema = {
type: 'object',
properties: {
email: {
rules: {
required: { value: true, message: 'Email is required' },
pattern: {
value: '^[^@]+@[^@]+\\.[^@]+$',
message: 'Invalid email format'
}
}
}
}
};
const eval = new JSONEval({ schema: JSON.stringify(schema) });
const data = { email: 'user@example.com' };
const result = await eval.evaluateJS({ data: JSON.stringify(data) });
const validation = await eval.validate({ data: JSON.stringify(data) });
if (!validation.has_error) {
console.log('â
Data is valid!');
}
eval.free(); // Clean up memory
React Native
import { useJSONEval } from '@json-eval-rs/react-native';
function ValidationForm() {
const eval = useJSONEval({ schema });
const [formData, setFormData] = useState({ name: '', age: '' });
const [errors, setErrors] = useState({});
const validateForm = async () => {
if (!eval) return;
const validation = await eval.validate({
data: JSON.stringify(formData)
});
setErrors(validation.errors || {});
};
return (
<View>
<TextInput
value={formData.name}
onChangeText={(name) => setFormData({ ...formData, name })}
onBlur={validateForm}
/>
{errors.name && <Text style={{color: 'red'}}>{errors.name.message}</Text>}
</View>
);
}
ðïļ Architecture
Core Components
- JSONEval: Main orchestrator handling the complete evaluation pipeline
- RLogic Engine: Custom JSON Logic compiler with pre-compilation and caching
- EvalData: Proxy-like data wrapper ensuring thread-safe mutations
- EvalCache: Content-based caching system using Arc for zero-copy storage
- Table Evaluator: Specialized parallel processing for table/array data
- Schema Parser: Extracts evaluations and builds dependency graphs
- Topological Sort: Groups evaluations into parallel-executable batches
Evaluation Pipeline
- Schema Parsing â Extract evaluations and build dependency graph
- Logic Compilation â Pre-compile JSON Logic expressions for performance
- Topological Sorting â Group evaluations into dependency-ordered batches
- Parallel Evaluation â Execute batches concurrently with caching
- Result Aggregation â Clean results and resolve layout references
⥠Performance
Benchmarks
| Operation | json-eval-rs | Native JS | Improvement |
|---|---|---|---|
| Parse Complex Schema | 3ms | 15ms | 5x faster |
| Evaluate 1000 Rules | 8ms | 45ms | 5.6x faster |
| Validate Large Form | 2ms | 12ms | 6x faster |
| Cache Hit Lookup | 0.1ms | 2ms | 20x faster |
Benchmarks run on Intel i7 with complex real-world schemas
Features Contributing to Performance
- Pre-compilation: JSON Logic expressions compiled once, evaluated many times
- Zero-Copy Caching: Results cached using
Arc<Value>to avoid deep cloning - Parallel Processing: Multi-threaded evaluation using
rayon(disabled for WASM) - SIMD JSON: Uses
simd-jsonfor ultra-fast JSON parsing - Smart Dependencies: Only re-evaluates fields when their dependencies change
ð§ Examples & CLI Tool
The library includes comprehensive examples demonstrating various use cases:
Basic Example
Simple evaluation with automatic scenario discovery:
# Run all scenarios
# Run specific scenario
# Enable comparison with expected results
Benchmark Example
Advanced benchmarking with ParsedSchema caching and concurrent testing:
# Run with 100 iterations
# Use ParsedSchema for efficient caching
# Test concurrent evaluations (4 threads, 10 iterations each)
# Full benchmarking suite with comparison
For more details, see examples/README.md.
CLI Tool
A powerful CLI tool for direct schema evaluation with parsed schema inspection:
# Simple evaluation
# With comparison and ParsedSchema
# Inspect parsed schema structure
# All parsed schema information
# Full options with MessagePack support
Parsed Schema Inspection Flags:
--print-sorted-evaluations- Show evaluation batches for parallel execution--print-dependencies- Show dependency graph between evaluations--print-tables- Show table definitions--print-evaluations- Show all compiled logic expressions--print-all- Show all parsed schema information
Run cargo run --bin json-eval-cli -- --help for full documentation.
Example Output
ð JSON Evaluation Benchmark
==============================
Scenario: zcc
Schema: samples/zcc.json
Data: samples/zcc-data.json
Loading files...
Running evaluation...
Schema parsing & compilation: 3.2ms
Total evaluation time: 12.4ms
Average per iteration: 124Ξs
Cache: 1,247 entries, 8,932 hits, 89 misses (99.0% hit rate)
âąïļ Execution time: 15.6ms
â
Results saved:
- samples/zcc-evaluated-schema.json
- samples/zcc-parsed-schema.json
- samples/zcc-evaluated-value.json
ð Platform Support
| Platform | Technology | Performance | Bundle Size |
|---|---|---|---|
| Rust | Native | Native | N/A |
| C# / .NET | P/Invoke FFI | Native | ~2MB |
| Web | WebAssembly | Near-native | ~450KB gzipped |
| React Native | Native Modules (JSI) | Native | Native code |
Supported Targets
- Linux: x86_64, ARM64
- Windows: x86_64
- macOS: x86_64, ARM64 (Apple Silicon)
- Web: All modern browsers, Node.js 14+
- Mobile: iOS 11+, Android API 21+
ðââïļ Getting Started
Prerequisites
- Rust: Latest stable (for core development)
- .NET SDK 6.0+: For C# bindings
- Node.js 18+: For Web/React Native bindings
- wasm-pack: For WebAssembly builds
Building from Source
# Clone the repository
# Build the core library
# Run tests
# Build all language bindings
# Run CLI tool with examples
ð Documentation
- API Documentation - Complete Rust API reference
- C# Documentation - .NET integration guide
- Web Documentation - JavaScript/TypeScript usage
- React Native Documentation - Mobile development guide
- Architecture Guide - Deep dive into internals
ðĪ Contributing
We welcome contributions! Please see our Contributing Guidelines for details.
Development Setup
- Fork and clone the repository
- Install dependencies:
cargo build - Run tests:
cargo test - Make your changes
- Add tests for new functionality
- Run
cargo fmtandcargo clippy - Submit a pull request
Building Bindings
# Build specific binding
# Package for publishing
ð Schema Format
json-eval-rs uses an extended JSON Schema format with evaluation rules:
Supported Rule Types
required: Field must have a valueminLength/maxLength: String/array length validationminValue/maxValue: Numeric range validationpattern: Regular expression validation- Custom rules via JSON Logic expressions
â ïļ Error Handling
The library provides detailed error information:
match eval.validate
ð License
This project is licensed under the MIT License - see the LICENSE file for details.
ðĒ Commercial Support
For commercial support, consulting, or custom development, please contact us at support@example.com.
ð Acknowledgments
- Built with Rust for maximum performance and safety
- Uses simd-json for high-speed JSON parsing
- Inspired by the JSON Logic specification
- WebAssembly bindings powered by wasm-bindgen
â Star this repository if you find it useful!