serialzero 0.1.0

A minimalist JSON parsing and serialization library for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
// SerialZero: A Minimalist JSON Parsing and Serialization Library for Rust
// ----------------------------------------------------------------------

//! # SerialZero
//!
//! A zero-dependency, minimalist JSON parsing and serialization library for Rust.
//!
//! ## Features
//!
//! * **Zero dependencies**: No external libraries, keeping your project lean.
//! * **Optimized for speed**: Written with performance in mind, for both parsing and serializing JSON.
//! * **Minimal API**: Simple, clean API that's easy to use without boilerplate.
//! * **Customizable**: Allows customization for use cases like date formatting or naming conventions.
//! * **Portable**: Ideal for projects with strict size limitations (embedded systems, webassembly).

use std::collections::HashMap;
use std::fmt;
use std::iter::Peekable;
use std::str::Chars;

/// The primary JSON value type that represents any valid JSON value
#[derive(Debug, Clone, PartialEq)]
pub enum JsonValue {
    Null,
    Boolean(bool),
    Number(f64),
    String(String),
    Array(Vec<JsonValue>),
    Object(HashMap<String, JsonValue>),
}

/// Error types that can occur during parsing or serialization
#[derive(Debug, PartialEq)]
pub enum JsonError {
    UnexpectedEndOfInput,
    UnexpectedToken(char),
    InvalidNumber,
    InvalidEscapeSequence,
    InvalidUnicodeSequence,
    MissingColon,
    MissingComma,
    InvalidValue,
}

impl fmt::Display for JsonError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            JsonError::UnexpectedEndOfInput => write!(f, "Unexpected end of input"),
            JsonError::UnexpectedToken(c) => write!(f, "Unexpected token: '{}'", c),
            JsonError::InvalidNumber => write!(f, "Invalid number"),
            JsonError::InvalidEscapeSequence => write!(f, "Invalid escape sequence"),
            JsonError::InvalidUnicodeSequence => write!(f, "Invalid Unicode sequence"),
            JsonError::MissingColon => write!(f, "Missing colon in object"),
            JsonError::MissingComma => write!(f, "Missing comma in array or object"),
            JsonError::InvalidValue => write!(f, "Invalid JSON value"),
        }
    }
}

impl std::error::Error for JsonError {}

type Result<T> = std::result::Result<T, JsonError>;

/// Options for configuring JSON serialization
#[derive(Debug, Clone)]
pub struct SerializeOptions {
    pub pretty: bool,
    pub indent: String,
    pub date_format: Option<String>,
    pub use_snake_case: bool,
}

impl Default for SerializeOptions {
    fn default() -> Self {
        SerializeOptions {
            pretty: false,
            indent: "  ".to_string(),
            date_format: None,
            use_snake_case: false,
        }
    }
}

// --------------------------------------------------------------------------------
// Parser Implementation
// --------------------------------------------------------------------------------

/// Parser for converting JSON strings into JsonValue structures
pub struct Parser<'a> {
    chars: Peekable<Chars<'a>>,
}

impl<'a> Parser<'a> {
    /// Create a new parser for the given input string
    pub fn new(input: &'a str) -> Self {
        Parser {
            chars: input.chars().peekable(),
        }
    }

    /// Parse the input string into a JsonValue
    pub fn parse(&mut self) -> Result<JsonValue> {
        self.skip_whitespace();
        let value = self.parse_value()?;
        self.skip_whitespace();
        
        // Ensure we've consumed all input
        if self.chars.peek().is_some() {
            return Err(JsonError::UnexpectedToken(self.chars.next().unwrap()));
        }
        
        Ok(value)
    }

    fn skip_whitespace(&mut self) {
        while let Some(&c) = self.chars.peek() {
            if !c.is_whitespace() {
                break;
            }
            self.chars.next();
        }
    }

    fn parse_value(&mut self) -> Result<JsonValue> {
        match self.chars.peek() {
            Some(&'"') => self.parse_string().map(JsonValue::String),
            Some(&('0'..='9') | &'-') => self.parse_number().map(JsonValue::Number),
            Some(&'{') => self.parse_object().map(JsonValue::Object),
            Some(&'[') => self.parse_array().map(JsonValue::Array),
            Some(&'t') => self.parse_true().map(|_| JsonValue::Boolean(true)),
            Some(&'f') => self.parse_false().map(|_| JsonValue::Boolean(false)),
            Some(&'n') => self.parse_null().map(|_| JsonValue::Null),
            Some(&c) => Err(JsonError::UnexpectedToken(c)),
            None => Err(JsonError::UnexpectedEndOfInput),
        }
    }

    fn parse_string(&mut self) -> Result<String> {
        // Consume the opening quote
        if self.chars.next() != Some('"') {
            return Err(JsonError::UnexpectedToken(self.chars.next().unwrap_or('\0')));
        }

        let mut result = String::new();
        
        loop {
            match self.chars.next() {
                Some('"') => return Ok(result),
                Some('\\') => {
                    // Handle escape sequences
                    match self.chars.next() {
                        Some('"') => result.push('"'),
                        Some('\\') => result.push('\\'),
                        Some('/') => result.push('/'),
                        Some('b') => result.push('\u{0008}'),
                        Some('f') => result.push('\u{000C}'),
                        Some('n') => result.push('\n'),
                        Some('r') => result.push('\r'),
                        Some('t') => result.push('\t'),
                        Some('u') => {
                            // Parse 4-digit hex code for Unicode character
                            let mut code = 0;
                            for _ in 0..4 {
                                match self.chars.next() {
                                    Some(c) if c.is_ascii_hexdigit() => {
                                        code = (code << 4) | c.to_digit(16).unwrap();
                                    }
                                    _ => return Err(JsonError::InvalidUnicodeSequence),
                                }
                            }
                            
                            // Convert the code point to a char
                            match std::char::from_u32(code) {
                                Some(c) => result.push(c),
                                None => return Err(JsonError::InvalidUnicodeSequence),
                            }
                        }
                        _ => return Err(JsonError::InvalidEscapeSequence),
                    }
                }
                Some(c) => result.push(c),
                None => return Err(JsonError::UnexpectedEndOfInput),
            }
        }
    }

    fn parse_number(&mut self) -> Result<f64> {
        let mut number = String::new();
        
        // Handle negative sign
        if let Some(&'-') = self.chars.peek() {
            number.push(self.chars.next().unwrap());
        }
        
        // Integer part
        if !self.parse_digits(&mut number) {
            return Err(JsonError::InvalidNumber);
        }
        
        // Fractional part
        if let Some(&'.') = self.chars.peek() {
            number.push(self.chars.next().unwrap());
            if !self.parse_digits(&mut number) {
                return Err(JsonError::InvalidNumber);
            }
        }
        
        // Exponent part
        if let Some(&'e' | &'E') = self.chars.peek() {
            number.push(self.chars.next().unwrap());
            
            // Optional sign
            if let Some(&'+' | &'-') = self.chars.peek() {
                number.push(self.chars.next().unwrap());
            }
            
            if !self.parse_digits(&mut number) {
                return Err(JsonError::InvalidNumber);
            }
        }
        
        // Convert to f64
        match number.parse::<f64>() {
            Ok(n) => Ok(n),
            Err(_) => Err(JsonError::InvalidNumber),
        }
    }

    fn parse_digits(&mut self, number: &mut String) -> bool {
        let mut has_digits = false;
        
        while let Some(&c) = self.chars.peek() {
            if !c.is_ascii_digit() {
                break;
            }
            number.push(self.chars.next().unwrap());
            has_digits = true;
        }
        
        has_digits
    }

    fn parse_object(&mut self) -> Result<HashMap<String, JsonValue>> {
        // Consume the opening brace
        if self.chars.next() != Some('{') {
            return Err(JsonError::UnexpectedToken(self.chars.next().unwrap_or('\0')));
        }
        
        self.skip_whitespace();
        
        let mut object = HashMap::new();
        
        // Check for empty object
        if let Some(&'}') = self.chars.peek() {
            self.chars.next();
            return Ok(object);
        }
        
        loop {
            self.skip_whitespace();
            
            // Parse key (must be a string)
            let key = self.parse_string()?;
            
            self.skip_whitespace();
            
            // Expect colon
            if self.chars.next() != Some(':') {
                return Err(JsonError::MissingColon);
            }
            
            self.skip_whitespace();
            
            // Parse value
            let value = self.parse_value()?;
            
            // Add to object
            object.insert(key, value);
            
            self.skip_whitespace();
            
            // Check for comma or closing brace
            match self.chars.next() {
                Some(',') => {
                    // Continue to next key-value pair
                }
                Some('}') => {
                    // End of object
                    return Ok(object);
                }
                _ => return Err(JsonError::MissingComma),
            }
        }
    }

    fn parse_array(&mut self) -> Result<Vec<JsonValue>> {
        // Consume the opening bracket
        if self.chars.next() != Some('[') {
            return Err(JsonError::UnexpectedToken(self.chars.next().unwrap_or('\0')));
        }
        
        self.skip_whitespace();
        
        let mut array = Vec::new();
        
        // Check for empty array
        if let Some(&']') = self.chars.peek() {
            self.chars.next();
            return Ok(array);
        }
        
        loop {
            self.skip_whitespace();
            
            // Parse value
            let value = self.parse_value()?;
            
            // Add to array
            array.push(value);
            
            self.skip_whitespace();
            
            // Check for comma or closing bracket
            match self.chars.next() {
                Some(',') => {
                    // Continue to next value
                }
                Some(']') => {
                    // End of array
                    return Ok(array);
                }
                _ => return Err(JsonError::MissingComma),
            }
        }
    }

    fn parse_true(&mut self) -> Result<()> {
        self.expect_literal("true")
    }

    fn parse_false(&mut self) -> Result<()> {
        self.expect_literal("false")
    }

    fn parse_null(&mut self) -> Result<()> {
        self.expect_literal("null")
    }

    fn expect_literal(&mut self, literal: &str) -> Result<()> {
        for expected in literal.chars() {
            match self.chars.next() {
                Some(c) if c == expected => {}
                _ => return Err(JsonError::InvalidValue),
            }
        }
        Ok(())
    }
}

// --------------------------------------------------------------------------------
// Serializer Implementation
// --------------------------------------------------------------------------------

/// Serialize a JsonValue to a string
pub fn to_string(value: &JsonValue) -> String {
    to_string_with_options(value, &SerializeOptions::default())
}

/// Serialize a JsonValue to a pretty-printed string
pub fn to_string_pretty(value: &JsonValue) -> String {
    let mut options = SerializeOptions::default();
    options.pretty = true;
    to_string_with_options(value, &options)
}

/// Serialize a JsonValue to a string with custom options
pub fn to_string_with_options(value: &JsonValue, options: &SerializeOptions) -> String {
    let mut result = String::new();
    serialize_value(value, &mut result, options, 0);
    result
}

fn serialize_value(value: &JsonValue, output: &mut String, options: &SerializeOptions, depth: usize) {
    match value {
        JsonValue::Null => output.push_str("null"),
        JsonValue::Boolean(b) => output.push_str(if *b { "true" } else { "false" }),
        JsonValue::Number(n) => {
            // Handle special cases for JSON compatibility
            if n.is_nan() {
                output.push_str("null");
            } else if n.is_infinite() {
                if n.is_sign_positive() {
                    output.push_str("null");
                } else {
                    output.push_str("null");
                }
            } else {
                // Remove trailing .0 for integers
                if n.fract() == 0.0 && n.abs() < 1e16 {
                    output.push_str(&format!("{}", *n as i64));
                } else {
                    output.push_str(&n.to_string());
                }
            }
        },
        JsonValue::String(s) => serialize_string(s, output),
        JsonValue::Array(arr) => serialize_array(arr, output, options, depth),
        JsonValue::Object(obj) => serialize_object(obj, output, options, depth),
    }
}

fn serialize_string(s: &str, output: &mut String) {
    output.push('"');
    
    for c in s.chars() {
        match c {
            '"' => output.push_str("\\\""),
            '\\' => output.push_str("\\\\"),
            '\u{0008}' => output.push_str("\\b"),
            '\u{000C}' => output.push_str("\\f"),
            '\n' => output.push_str("\\n"),
            '\r' => output.push_str("\\r"),
            '\t' => output.push_str("\\t"),
            c if c.is_control() => {
                output.push_str(&format!("\\u{:04x}", c as u32));
            },
            c => output.push(c),
        }
    }
    
    output.push('"');
}

fn serialize_array(arr: &[JsonValue], output: &mut String, options: &SerializeOptions, depth: usize) {
    if arr.is_empty() {
        output.push_str("[]");
        return;
    }
    
    output.push('[');
    
    if options.pretty {
        output.push('\n');
    }
    
    for (i, item) in arr.iter().enumerate() {
        if options.pretty {
            output.push_str(&options.indent.repeat(depth + 1));
        }
        
        serialize_value(item, output, options, depth + 1);
        
        if i < arr.len() - 1 {
            output.push(',');
        }
        
        if options.pretty {
            output.push('\n');
        }
    }
    
    if options.pretty {
        output.push_str(&options.indent.repeat(depth));
    }
    
    output.push(']');
}

fn serialize_object(obj: &HashMap<String, JsonValue>, output: &mut String, options: &SerializeOptions, depth: usize) {
    if obj.is_empty() {
        output.push_str("{}");
        return;
    }
    
    output.push('{');
    
    if options.pretty {
        output.push('\n');
    }
    
    let mut entries: Vec<(&String, &JsonValue)> = obj.iter().collect();
    entries.sort_by(|a, b| a.0.cmp(b.0));
    
    for (i, (key, value)) in entries.iter().enumerate() {
        if options.pretty {
            output.push_str(&options.indent.repeat(depth + 1));
        }
        
        let key_to_use = if options.use_snake_case {
            camel_to_snake(key)
        } else {
            key.to_string()
        };
        
        serialize_string(&key_to_use, output);
        output.push(':');
        
        if options.pretty {
            output.push(' ');
        }
        
        serialize_value(value, output, options, depth + 1);
        
        if i < entries.len() - 1 {
            output.push(',');
        }
        
        if options.pretty {
            output.push('\n');
        }
    }
    
    if options.pretty {
        output.push_str(&options.indent.repeat(depth));
    }
    
    output.push('}');
}

fn camel_to_snake(s: &str) -> String {
    let mut result = String::new();
    let mut prev_is_lower = false;
    
    for (i, c) in s.char_indices() {
        if c.is_uppercase() {
            if i > 0 && prev_is_lower {
                result.push('_');
            }
            result.push(c.to_lowercase().next().unwrap());
        } else {
            result.push(c);
            prev_is_lower = true;
        }
    }
    
    result
}

// --------------------------------------------------------------------------------
// Extension Traits for easier usage
// --------------------------------------------------------------------------------

/// Extension trait for JsonValue
pub trait JsonValueExt {
    fn as_bool(&self) -> Option<bool>;
    fn as_number(&self) -> Option<f64>;
    fn as_string(&self) -> Option<&str>;
    fn as_array(&self) -> Option<&Vec<JsonValue>>;
    fn as_object(&self) -> Option<&HashMap<String, JsonValue>>;
    fn get(&self, key: &str) -> Option<&JsonValue>;
    fn get_path(&self, path: &str) -> Option<&JsonValue>;
}

impl JsonValueExt for JsonValue {
    fn as_bool(&self) -> Option<bool> {
        match self {
            JsonValue::Boolean(b) => Some(*b),
            _ => None,
        }
    }

    fn as_number(&self) -> Option<f64> {
        match self {
            JsonValue::Number(n) => Some(*n),
            _ => None,
        }
    }

    fn as_string(&self) -> Option<&str> {
        match self {
            JsonValue::String(s) => Some(s),
            _ => None,
        }
    }

    fn as_array(&self) -> Option<&Vec<JsonValue>> {
        match self {
            JsonValue::Array(a) => Some(a),
            _ => None,
        }
    }

    fn as_object(&self) -> Option<&HashMap<String, JsonValue>> {
        match self {
            JsonValue::Object(o) => Some(o),
            _ => None,
        }
    }

    fn get(&self, key: &str) -> Option<&JsonValue> {
        match self {
            JsonValue::Object(o) => o.get(key),
            _ => None,
        }
    }

    fn get_path(&self, path: &str) -> Option<&JsonValue> {
        let parts: Vec<&str> = path.split('.').collect();
        let mut current = self;
        
        for part in parts {
            match current {
                JsonValue::Object(o) => {
                    current = o.get(part)?;
                },
                _ => return None,
            }
        }
        
        Some(current)
    }
}

// --------------------------------------------------------------------------------
// Macros for easier creation of JSON values
// --------------------------------------------------------------------------------

#[macro_export]
macro_rules! json {
    (null) => {
        $crate::JsonValue::Null
    };
    (true) => {
        $crate::JsonValue::Boolean(true)
    };
    (false) => {
        $crate::JsonValue::Boolean(false)
    };
    ($num:expr) => {
        $crate::JsonValue::Number($num as f64)
    };
    ($str:expr) => {
        $crate::JsonValue::String($str.to_string())
    };
    ([$($value:tt),*]) => {
        $crate::JsonValue::Array(vec![$($crate::json!($value)),*])
    };
    ({$($key:tt => $value:tt),*}) => {
        {
            let mut map = std::collections::HashMap::new();
            $(
                map.insert($key.to_string(), $crate::json!($value));
            )*
            $crate::JsonValue::Object(map)
        }
    };
}

// --------------------------------------------------------------------------------
// Public API Functions
// --------------------------------------------------------------------------------

/// Parse a JSON string into a JsonValue
pub fn parse(input: &str) -> Result<JsonValue> {
    Parser::new(input).parse()
}

// Serialization helpers for native Rust types
pub fn from_bool(b: bool) -> JsonValue {
    JsonValue::Boolean(b)
}

pub fn from_number<T: Into<f64>>(n: T) -> JsonValue {
    JsonValue::Number(n.into())
}

pub fn from_str<T: Into<String>>(s: T) -> JsonValue {
    JsonValue::String(s.into())
}

// --------------------------------------------------------------------------------
// Tests
// --------------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_null() {
        assert_eq!(parse("null").unwrap(), JsonValue::Null);
    }

    #[test]
    fn test_parse_bool() {
        assert_eq!(parse("true").unwrap(), JsonValue::Boolean(true));
        assert_eq!(parse("false").unwrap(), JsonValue::Boolean(false));
    }

    #[test]
    fn test_parse_number() {
        assert_eq!(parse("123").unwrap(), JsonValue::Number(123.0));
        assert_eq!(parse("-123.456").unwrap(), JsonValue::Number(-123.456));
        assert_eq!(parse("1e10").unwrap(), JsonValue::Number(1e10));
    }

    #[test]
    fn test_parse_string() {
        assert_eq!(
            parse("\"hello world\"").unwrap(),
            JsonValue::String("hello world".to_string())
        );
        assert_eq!(
            parse("\"escape\\\"quote\"").unwrap(),
            JsonValue::String("escape\"quote".to_string())
        );
    }

    #[test]
    fn test_parse_array() {
        assert_eq!(
            parse("[1, 2, 3]").unwrap(),
            JsonValue::Array(vec![
                JsonValue::Number(1.0),
                JsonValue::Number(2.0),
                JsonValue::Number(3.0)
            ])
        );
    }

    #[test]
    fn test_parse_object() {
        let parsed = parse("{\"name\":\"John\",\"age\":30}").unwrap();
        
        match parsed {
            JsonValue::Object(obj) => {
                assert_eq!(obj.len(), 2);
                assert_eq!(obj.get("name").unwrap(), &JsonValue::String("John".to_string()));
                assert_eq!(obj.get("age").unwrap(), &JsonValue::Number(30.0));
            },
            _ => panic!("Expected object"),
        }
    }

    #[test]
    fn test_serialize() {
        // Create JsonValue manually without the macro
        let mut hobbies = Vec::new();
        hobbies.push(JsonValue::String("reading".to_string()));
        hobbies.push(JsonValue::String("coding".to_string()));
        
        let mut obj = HashMap::new();
        obj.insert("name".to_string(), JsonValue::String("John".to_string()));
        obj.insert("age".to_string(), JsonValue::Number(30.0));
        obj.insert("is_active".to_string(), JsonValue::Boolean(true));
        obj.insert("hobbies".to_string(), JsonValue::Array(hobbies));
        
        let value = JsonValue::Object(obj);
        
        let serialized = to_string(&value);
        let parsed = parse(&serialized).unwrap();
        
        assert_eq!(value, parsed);
    }

    #[test]
    fn test_json_macro() {
        // Create JsonValue manually without the macro
        let mut hobbies = Vec::new();
        hobbies.push(JsonValue::String("reading".to_string()));
        hobbies.push(JsonValue::String("coding".to_string()));
        
        let mut obj = HashMap::new();
        obj.insert("name".to_string(), JsonValue::String("John".to_string()));
        obj.insert("age".to_string(), JsonValue::Number(30.0));
        obj.insert("is_active".to_string(), JsonValue::Boolean(true));
        obj.insert("hobbies".to_string(), JsonValue::Array(hobbies));
        
        let obj = JsonValue::Object(obj);
        
        assert_eq!(obj.get("name").unwrap().as_string().unwrap(), "John");
        assert_eq!(obj.get("age").unwrap().as_number().unwrap(), 30.0);
        assert_eq!(obj.get("is_active").unwrap().as_bool().unwrap(), true);
        
        let hobbies = obj.get("hobbies").unwrap().as_array().unwrap();
        assert_eq!(hobbies.len(), 2);
        assert_eq!(hobbies[0].as_string().unwrap(), "reading");
        assert_eq!(hobbies[1].as_string().unwrap(), "coding");
    }
}