Skip to main content

json_validation_demo/
json_validation_demo.rs

1//! JSON Validation Demo
2//!
3//! Demonstrates fast JSON validation without memory allocation.
4//! Useful for embedded systems to reject invalid data early.
5
6use babbel_json::{BufferSource, ParserConfig, validate_json};
7
8fn main() {
9    println!("=== JSON Validation Demo ===\n");
10
11    // Example 1: Valid simple JSON
12    println!("1. Validating simple JSON:");
13    let json1 = br#"{"name": "Alice", "age": 30, "active": true}"#;
14    match validate_simple(json1) {
15        Ok(_) => println!("   ✓ Valid JSON\n"),
16        Err(e) => println!("   ✗ Invalid: {}\n", e),
17    }
18
19    // Example 2: Valid nested JSON
20    println!("2. Validating nested structure:");
21    let json2 = br#"{
22        "user": {
23            "name": "Bob",
24            "settings": {
25                "theme": "dark",
26                "notifications": true
27            }
28        },
29        "devices": ["phone", "tablet", "laptop"]
30    }"#;
31    match validate_simple(json2) {
32        Ok(_) => println!("   ✓ Valid JSON\n"),
33        Err(e) => println!("   ✗ Invalid: {}\n", e),
34    }
35
36    // Example 3: Invalid JSON - missing quote
37    println!("3. Detecting invalid JSON (missing quote):");
38    let json3 = br#"{"name: "Alice"}"#;
39    match validate_simple(json3) {
40        Ok(_) => println!("   ✓ Valid JSON\n"),
41        Err(e) => println!("   ✗ Invalid: {}\n", e),
42    }
43
44    // Example 4: Invalid JSON - trailing comma
45    println!("4. Detecting trailing comma:");
46    let json4 = br#"{"a": 1, "b": 2,}"#;
47    match validate_simple(json4) {
48        Ok(_) => println!("   ✓ Valid JSON\n"),
49        Err(e) => println!("   ✗ Invalid: {}\n", e),
50    }
51
52    // Example 5: Configuration limits - depth
53    println!("5. Checking depth limits:");
54    let deep_json = br#"{"a":{"b":{"c":{"d":{"e":1}}}}}"#;
55    let mut source = BufferSource::new(deep_json);
56    let shallow_config = ParserConfig::new().with_max_depth(Some(3));
57
58    match validate_json(&mut source, &shallow_config) {
59        Ok(_) => println!("   ✓ Within depth limit\n"),
60        Err(e) => println!("   ✗ Exceeds limit: {}\n", e),
61    }
62
63    // Example 6: Configuration limits - string length
64    println!("6. Checking string length limits:");
65    let long_string = format!(r#"{{"data": "{}"}}"#, "x".repeat(300));
66    let mut source = BufferSource::new(long_string.as_bytes());
67    let strict_config = ParserConfig::strict(); // max 256 bytes
68
69    match validate_json(&mut source, &strict_config) {
70        Ok(_) => println!("   ✓ Within string limit\n"),
71        Err(e) => println!("   ✗ Exceeds limit: {}\n", e),
72    }
73
74    // Example 7: Valid number formats
75    println!("7. Validating various number formats:");
76    let numbers: Vec<(&[u8], &str)> = vec![
77        (b"123", "integer"),
78        (b"-456", "negative"),
79        (b"3.14", "decimal"),
80        (b"1e10", "exponential"),
81        (b"2.5e-3", "scientific"),
82    ];
83
84    for (json, desc) in numbers {
85        let mut source = BufferSource::new(json);
86        let config = ParserConfig::new();
87        match validate_json(&mut source, &config) {
88            Ok(_) => println!("   ✓ {} ({})", std::str::from_utf8(json).unwrap(), desc),
89            Err(e) => println!("   ✗ {}: {}", desc, e),
90        }
91    }
92    println!();
93
94    // Example 8: Invalid number formats
95    println!("8. Detecting invalid numbers:");
96    let invalid_numbers: Vec<(&[u8], &str)> = vec![
97        (b"01", "leading zero"),
98        (b"-.5", "no digit before decimal"),
99        (b"1.", "no digit after decimal"),
100    ];
101
102    for (json, desc) in invalid_numbers {
103        let mut source = BufferSource::new(json);
104        let config = ParserConfig::new();
105        match validate_json(&mut source, &config) {
106            Ok(_) => println!("   ✗ Should have failed: {}", desc),
107            Err(e) => println!("   ✓ Correctly rejected {}: {}", desc, e),
108        }
109    }
110    println!();
111
112    // Example 9: Large array validation
113    println!("9. Validating array size limits:");
114    let large_array = format!(
115        "[{}]",
116        (0..100)
117            .map(|i| i.to_string())
118            .collect::<Vec<_>>()
119            .join(",")
120    );
121    let mut source = BufferSource::new(large_array.as_bytes());
122    let small_config = ParserConfig::strict().with_max_array_size(Some(50));
123
124    match validate_json(&mut source, &small_config) {
125        Ok(_) => println!("   ✓ Within array limit\n"),
126        Err(e) => println!("   ✗ Exceeds limit: {}\n", e),
127    }
128
129    // Example 10: Embedded use case - sensor data validation
130    println!("10. Embedded use case - validating sensor data:");
131    let sensor_readings: Vec<&[u8]> = vec![
132        br#"{"id":"temp_01","value":23.5,"ts":1234567890}"#.as_slice(),
133        br#"{"id":"hum_02","value":45.2,"ts":1234567891}"#.as_slice(),
134        br#"{"id":"bad","value":,"ts":123}"#.as_slice(), // Invalid
135    ];
136
137    let config = ParserConfig::strict();
138    for (i, reading) in sensor_readings.iter().enumerate() {
139        let mut source = BufferSource::new(*reading);
140        match validate_json(&mut source, &config) {
141            Ok(_) => println!("   ✓ Reading {} is valid", i + 1),
142            Err(e) => println!("   ✗ Reading {} invalid: {}", i + 1, e),
143        }
144    }
145
146    println!("\n=== Validation complete ===");
147}
148
149fn validate_simple(json: &[u8]) -> Result<(), String> {
150    let mut source = BufferSource::new(json);
151    let config = ParserConfig::new();
152    validate_json(&mut source, &config)
153}