json_object 0.1.1

A Simple JsonObject 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
// =============================================================================
//  Usage: just copy this file into your project and `mod json_object;`
// =============================================================================
//
//  Quick Start:
//
//  use json_object::*;
//
//  // Build with macro:
//  let obj = json!({
//      "name": "Rebon402",
//      "age": 30,
//      "scores": [10, 20, 30],
//      "active": true,
//      "address": {
//          "city": "Bangkok"
//      }
//  });
//
//  // Access values:
//  println!("{}", obj["name"].as_str().unwrap());   // "Rebon402"
//  println!("{}", obj["age"].as_i64().unwrap());    // 30
//
//  // Dot-path access:
//  println!("{}", obj.get_path("address.city").unwrap()); // Json::Str("Bangkok")
//
//  // Serialize:
//  println!("{}", obj.to_json());
//
//  // Parse:
//  let parsed = Json::parse(r#"{"key": 123}"#).unwrap();
// =============================================================================

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

// ─── Core Type ────────────────────────────────────────────────────────────────

/// The main JSON value type.
#[derive(Debug, Clone, PartialEq)]
pub enum Json {
    Null,
    Bool(bool),
    Int(i64),
    Float(f64),
    Str(String),
    Array(Vec<Json>),
    Object(HashMap<String, Json>),
}

// ─── Construction helpers ─────────────────────────────────────────────────────

impl Json {
    pub fn null() -> Self { Json::Null }
    pub fn bool(v: bool) -> Self { Json::Bool(v) }
    pub fn int(v: i64) -> Self { Json::Int(v) }
    pub fn float(v: f64) -> Self { Json::Float(v) }
    pub fn str(v: impl Into<String>) -> Self { Json::Str(v.into()) }
    pub fn array(v: Vec<Json>) -> Self { Json::Array(v) }
    pub fn object(v: HashMap<String, Json>) -> Self { Json::Object(v) }

    /// Create an empty object.
    pub fn new_object() -> Self { Json::Object(HashMap::new()) }

    /// Create an empty array.
    pub fn new_array() -> Self { Json::Array(Vec::new()) }
}

// ─── Type checks ─────────────────────────────────────────────────────────────

impl Json {
    pub fn is_null(&self) -> bool   { matches!(self, Json::Null) }
    pub fn is_bool(&self) -> bool   { matches!(self, Json::Bool(_)) }
    pub fn is_int(&self) -> bool    { matches!(self, Json::Int(_)) }
    pub fn is_float(&self) -> bool  { matches!(self, Json::Float(_)) }
    pub fn is_number(&self) -> bool { self.is_int() || self.is_float() }
    pub fn is_str(&self) -> bool    { matches!(self, Json::Str(_)) }
    pub fn is_array(&self) -> bool  { matches!(self, Json::Array(_)) }
    pub fn is_object(&self) -> bool { matches!(self, Json::Object(_)) }
}

// ─── Value extraction ─────────────────────────────────────────────────────────

impl Json {
    pub fn as_bool(&self) -> Option<bool> {
        if let Json::Bool(v) = self { Some(*v) } else { None }
    }

    pub fn as_i64(&self) -> Option<i64> {
        match self {
            Json::Int(v)   => Some(*v),
            Json::Float(v) => Some(*v as i64),
            _ => None,
        }
    }

    pub fn as_f64(&self) -> Option<f64> {
        match self {
            Json::Float(v) => Some(*v),
            Json::Int(v)   => Some(*v as f64),
            _ => None,
        }
    }

    pub fn as_str(&self) -> Option<&str> {
        if let Json::Str(v) = self { Some(v) } else { None }
    }

    pub fn as_array(&self) -> Option<&Vec<Json>> {
        if let Json::Array(v) = self { Some(v) } else { None }
    }

    pub fn as_array_mut(&mut self) -> Option<&mut Vec<Json>> {
        if let Json::Array(v) = self { Some(v) } else { None }
    }

    pub fn as_object(&self) -> Option<&HashMap<String, Json>> {
        if let Json::Object(v) = self { Some(v) } else { None }
    }

    pub fn as_object_mut(&mut self) -> Option<&mut HashMap<String, Json>> {
        if let Json::Object(v) = self { Some(v) } else { None }
    }

    /// Returns `Json::Null` instead of panicking.
    pub fn get(&self, key: &str) -> &Json {
        match self {
            Json::Object(map) => map.get(key).unwrap_or(&Json::Null),
            _ => &Json::Null,
        }
    }

    /// Deep dot-path access: `obj.get_path("user.address.city")`
    pub fn get_path(&self, path: &str) -> Option<&Json> {
        let mut current = self;
        for key in path.split('.') {
            match current {
                Json::Object(map) => {
                    current = map.get(key)?;
                }
                Json::Array(arr) => {
                    let idx: usize = key.parse().ok()?;
                    current = arr.get(idx)?;
                }
                _ => return None,
            }
        }
        Some(current)
    }

    /// Returns the number of keys (object) or elements (array).
    pub fn len(&self) -> usize {
        match self {
            Json::Object(m) => m.len(),
            Json::Array(a)  => a.len(),
            Json::Str(s)    => s.len(),
            _ => 0,
        }
    }

    pub fn is_empty(&self) -> bool { self.len() == 0 }
}

// ─── Mutation helpers ─────────────────────────────────────────────────────────

impl Json {
    /// Set a key on an Object. Panics if `self` is not an Object.
    pub fn set(&mut self, key: impl Into<String>, value: impl Into<Json>) -> &mut Self {
        if let Json::Object(map) = self {
            map.insert(key.into(), value.into());
        } else {
            panic!("Json::set called on non-Object");
        }
        self
    }

    /// Remove a key from an Object. Returns the removed value if it existed.
    pub fn remove(&mut self, key: &str) -> Option<Json> {
        if let Json::Object(map) = self {
            map.remove(key)
        } else {
            None
        }
    }

    /// Append a value to an Array. Panics if `self` is not an Array.
    pub fn push(&mut self, value: impl Into<Json>) -> &mut Self {
        if let Json::Array(arr) = self {
            arr.push(value.into());
        } else {
            panic!("Json::push called on non-Array");
        }
        self
    }

    /// Merge another object's keys into this one (shallow). Returns &mut Self for chaining.
    pub fn merge(&mut self, other: &Json) -> &mut Self {
        if let (Json::Object(dst), Json::Object(src)) = (&mut *self, other) {
            for (k, v) in src {
                dst.insert(k.clone(), v.clone());
            }
        }
        self
    }

    /// Returns true if an Object contains the key.
    pub fn contains_key(&self, key: &str) -> bool {
        matches!(self, Json::Object(m) if m.contains_key(key))
    }
}

// ─── Iteration helpers ────────────────────────────────────────────────────────

impl Json {
    /// Iterate over array elements.
    pub fn iter_array(&self) -> impl Iterator<Item = &Json> {
        match self {
            Json::Array(v) => v.iter(),
            _ => [].iter(),
        }
    }

    /// Iterate over object (key, value) pairs.
    pub fn iter_object(&self) -> impl Iterator<Item = (&String, &Json)> {
        static EMPTY: std::sync::OnceLock<HashMap<String, Json>> = std::sync::OnceLock::new();
        match self {
            Json::Object(m) => m.iter(),
            _ => EMPTY.get_or_init(HashMap::new).iter(),
        }
    }

    /// Collect all object keys.
    pub fn keys(&self) -> Vec<&String> {
        match self {
            Json::Object(m) => m.keys().collect(),
            _ => vec![],
        }
    }

    /// Collect all object values.
    pub fn values(&self) -> Vec<&Json> {
        match self {
            Json::Object(m) => m.values().collect(),
            _ => vec![],
        }
    }
}

// ─── Serialisation ────────────────────────────────────────────────────────────

impl Json {
    /// Compact JSON string.
    pub fn to_json(&self) -> String {
        let mut buf = String::new();
        self.write_json(&mut buf, None, 0);
        buf
    }

    /// Pretty-printed JSON with custom indent (e.g. `"  "` or `"\t"`).
    pub fn to_pretty(&self, indent: &str) -> String {
        let mut buf = String::new();
        self.write_json(&mut buf, Some(indent), 0);
        buf
    }

    fn write_json(&self, buf: &mut String, indent: Option<&str>, depth: usize) {
        match self {
            Json::Null        => buf.push_str("null"),
            Json::Bool(b)     => buf.push_str(if *b { "true" } else { "false" }),
            Json::Int(n)      => buf.push_str(&n.to_string()),
            Json::Float(f)    => {
                if f.fract() == 0.0 && f.is_finite() {
                    buf.push_str(&format!("{:.1}", f));
                } else {
                    buf.push_str(&f.to_string());
                }
            }
            Json::Str(s)      => {
                buf.push('"');
                for c in s.chars() {
                    match c {
                        '"'  => buf.push_str("\\\""),
                        '\\' => buf.push_str("\\\\"),
                        '\n' => buf.push_str("\\n"),
                        '\r' => buf.push_str("\\r"),
                        '\t' => buf.push_str("\\t"),
                        c if (c as u32) < 0x20 => {
                            buf.push_str(&format!("\\u{:04x}", c as u32));
                        }
                        c => buf.push(c),
                    }
                }
                buf.push('"');
            }
            Json::Array(arr)  => {
                if arr.is_empty() { buf.push_str("[]"); return; }
                buf.push('[');
                for (i, v) in arr.iter().enumerate() {
                    if let Some(ind) = indent {
                        buf.push('\n');
                        for _ in 0..=depth { buf.push_str(ind); }
                    }
                    v.write_json(buf, indent, depth + 1);
                    if i + 1 < arr.len() { buf.push(','); }
                }
                if let Some(ind) = indent {
                    buf.push('\n');
                    for _ in 0..depth { buf.push_str(ind); }
                }
                buf.push(']');
            }
            Json::Object(map) => {
                if map.is_empty() { buf.push_str("{}"); return; }
                buf.push('{');
                let mut keys: Vec<&String> = map.keys().collect();
                keys.sort(); // deterministic output
                for (i, k) in keys.iter().enumerate() {
                    if let Some(ind) = indent {
                        buf.push('\n');
                        for _ in 0..=depth { buf.push_str(ind); }
                    }
                    // write key
                    let key_json = Json::Str(k.to_string());
                    key_json.write_json(buf, indent, depth + 1);
                    buf.push(':');
                    if indent.is_some() { buf.push(' '); }
                    map[*k].write_json(buf, indent, depth + 1);
                    if i + 1 < keys.len() { buf.push(','); }
                }
                if let Some(ind) = indent {
                    buf.push('\n');
                    for _ in 0..depth { buf.push_str(ind); }
                }
                buf.push('}');
            }
        }
    }
}

// ─── fmt::Display ─────────────────────────────────────────────────────────────

impl fmt::Display for Json {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_json())
    }
}

// ─── From conversions ─────────────────────────────────────────────────────────

impl From<bool>    for Json { fn from(v: bool)    -> Self { Json::Bool(v) } }
impl From<i64>     for Json { fn from(v: i64)     -> Self { Json::Int(v) } }
impl From<i32>     for Json { fn from(v: i32)     -> Self { Json::Int(v as i64) } }
impl From<u64>     for Json { fn from(v: u64)     -> Self { Json::Int(v as i64) } }
impl From<usize>   for Json { fn from(v: usize)   -> Self { Json::Int(v as i64) } }
impl From<f64>     for Json { fn from(v: f64)     -> Self { Json::Float(v) } }
impl From<f32>     for Json { fn from(v: f32)     -> Self { Json::Float(v as f64) } }
impl From<String>  for Json { fn from(v: String)  -> Self { Json::Str(v) } }
impl From<&str>    for Json { fn from(v: &str)    -> Self { Json::Str(v.to_owned()) } }
impl<T: Into<Json>> From<Vec<T>> for Json {
    fn from(v: Vec<T>) -> Self { Json::Array(v.into_iter().map(Into::into).collect()) }
}
impl<T: Into<Json>> From<Option<T>> for Json {
    fn from(v: Option<T>) -> Self { v.map(Into::into).unwrap_or(Json::Null) }
}

// ─── Index operator ───────────────────────────────────────────────────────────

impl std::ops::Index<&str> for Json {
    type Output = Json;
    fn index(&self, key: &str) -> &Json { self.get(key) }
}

impl std::ops::Index<usize> for Json {
    type Output = Json;
    fn index(&self, idx: usize) -> &Json {
        match self {
            Json::Array(arr) => arr.get(idx).unwrap_or(&Json::Null),
            _ => &Json::Null,
        }
    }
}

// ─── Parser ───────────────────────────────────────────────────────────────────

#[derive(Debug)]
pub struct ParseError(pub String);
impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "ParseError: {}", self.0) } }
impl std::error::Error for ParseError {}

impl Json {
    /// Parse a JSON string into a `Json` value.
    pub fn parse(src: &str) -> Result<Json, ParseError> {
        let mut chars = src.chars().peekable();
        let val = parse_value(&mut chars)?;
        skip_ws(&mut chars);
        if chars.peek().is_some() {
            return Err(ParseError("trailing characters after JSON value".into()));
        }
        Ok(val)
    }
}

type Iter<'a> = Peekable<Chars<'a>>;

fn skip_ws(it: &mut Iter) {
    while matches!(it.peek(), Some(' ' | '\t' | '\n' | '\r')) { it.next(); }
}

fn parse_value(it: &mut Iter) -> Result<Json, ParseError> {
    skip_ws(it);
    match it.peek().copied() {
        Some('"')              => parse_string(it).map(Json::Str),
        Some('{')              => parse_object(it),
        Some('[')              => parse_array(it),
        Some('t')              => { expect_str(it, "true")?;  Ok(Json::Bool(true)) }
        Some('f')              => { expect_str(it, "false")?; Ok(Json::Bool(false)) }
        Some('n')              => { expect_str(it, "null")?;  Ok(Json::Null) }
        Some(c) if c == '-' || c.is_ascii_digit() => parse_number(it),
        Some(c) => Err(ParseError(format!("unexpected character '{}'", c))),
        None    => Err(ParseError("unexpected end of input".into())),
    }
}

fn expect_str(it: &mut Iter, s: &str) -> Result<(), ParseError> {
    for c in s.chars() {
        match it.next() {
            Some(x) if x == c => {}
            other => return Err(ParseError(format!("expected '{}', got {:?}", c, other))),
        }
    }
    Ok(())
}

fn parse_string(it: &mut Iter) -> Result<String, ParseError> {
    it.next(); // consume '"'
    let mut out = String::new();
    loop {
        match it.next() {
            Some('"')  => return Ok(out),
            Some('\\') => {
                match it.next() {
                    Some('"')  => out.push('"'),
                    Some('\\') => out.push('\\'),
                    Some('/')  => out.push('/'),
                    Some('n')  => out.push('\n'),
                    Some('r')  => out.push('\r'),
                    Some('t')  => out.push('\t'),
                    Some('b')  => out.push('\x08'),
                    Some('f')  => out.push('\x0C'),
                    Some('u')  => {
                        let hex: String = (0..4).filter_map(|_| it.next()).collect();
                        if hex.len() != 4 {
                            return Err(ParseError("invalid \\u escape".into()));
                        }
                        let codepoint = u32::from_str_radix(&hex, 16)
                            .map_err(|_| ParseError(format!("invalid hex '{}'", hex)))?;
                        let ch = char::from_u32(codepoint)
                            .ok_or_else(|| ParseError(format!("invalid codepoint U+{:04X}", codepoint)))?;
                        out.push(ch);
                    }
                    Some(c) => return Err(ParseError(format!("invalid escape '\\{}'", c))),
                    None    => return Err(ParseError("unterminated string".into())),
                }
            }
            Some(c)   => out.push(c),
            None       => return Err(ParseError("unterminated string".into())),
        }
    }
}

fn parse_number(it: &mut Iter) -> Result<Json, ParseError> {
    let mut s = String::new();
    if it.peek() == Some(&'-') { s.push(it.next().unwrap()); }
    while matches!(it.peek(), Some('0'..='9')) { s.push(it.next().unwrap()); }
    let is_float = matches!(it.peek(), Some('.') | Some('e') | Some('E'));
    if is_float {
        if it.peek() == Some(&'.') {
            s.push(it.next().unwrap());
            while matches!(it.peek(), Some('0'..='9')) { s.push(it.next().unwrap()); }
        }
        if matches!(it.peek(), Some('e') | Some('E')) {
            s.push(it.next().unwrap());
            if matches!(it.peek(), Some('+') | Some('-')) { s.push(it.next().unwrap()); }
            while matches!(it.peek(), Some('0'..='9')) { s.push(it.next().unwrap()); }
        }
        s.parse::<f64>().map(Json::Float).map_err(|_| ParseError(format!("invalid float '{}'", s)))
    } else {
        s.parse::<i64>().map(Json::Int).map_err(|_| ParseError(format!("invalid int '{}'", s)))
    }
}

fn parse_array(it: &mut Iter) -> Result<Json, ParseError> {
    it.next(); // consume '['
    let mut arr = Vec::new();
    skip_ws(it);
    if it.peek() == Some(&']') { it.next(); return Ok(Json::Array(arr)); }
    loop {
        arr.push(parse_value(it)?);
        skip_ws(it);
        match it.peek() {
            Some(',') => { it.next(); }
            Some(']') => { it.next(); return Ok(Json::Array(arr)); }
            other     => return Err(ParseError(format!("expected ',' or ']', got {:?}", other))),
        }
    }
}

fn parse_object(it: &mut Iter) -> Result<Json, ParseError> {
    it.next(); // consume '{'
    let mut map = HashMap::new();
    skip_ws(it);
    if it.peek() == Some(&'}') { it.next(); return Ok(Json::Object(map)); }
    loop {
        skip_ws(it);
        if it.peek() != Some(&'"') {
            return Err(ParseError(format!("expected key string, got {:?}", it.peek())));
        }
        let key = parse_string(it)?;
        skip_ws(it);
        if it.next() != Some(':') {
            return Err(ParseError("expected ':' after object key".into()));
        }
        let val = parse_value(it)?;
        map.insert(key, val);
        skip_ws(it);
        match it.peek() {
            Some(',') => { it.next(); }
            Some('}') => { it.next(); return Ok(Json::Object(map)); }
            other     => return Err(ParseError(format!("expected ',' or '}}', got {:?}", other))),
        }
    }
}

// ─── json! macro ──────────────────────────────────────────────────────────────

/// Build a `Json` value with a JSON-like literal syntax.
///
/// ```
/// use json_object::{Json, json};
/// let v = json!({
///     "name": "Bob",
///     "scores": [1i64, 2i64, 3i64],
///     "meta": { "active": true, "rating": 4.5f64 },
///     "nothing": null
/// });
/// assert_eq!(v["name"].as_str(), Some("Bob"));
/// ```
#[macro_export]
macro_rules! json {
    (null)  => { $crate::Json::Null };
    (true)  => { $crate::Json::Bool(true) };
    (false) => { $crate::Json::Bool(false) };

    // Array
    ([ $($elem:tt),* $(,)? ]) => {
        $crate::Json::Array(vec![ $( json!($elem) ),* ])
    };

    // Object
    ({ $($key:tt : $val:tt),* $(,)? }) => {{
        let mut _map = ::std::collections::HashMap::new();
        $( _map.insert(String::from($key), json!($val)); )*
        $crate::Json::Object(_map)
    }};

    // Expressions (variables, function calls, literals)
    ($other:expr) => { $crate::Json::from($other) };
}

// ─── ObjectBuilder — fluent API ───────────────────────────────────────────────

/// Fluent builder for JSON objects.
///
/// ```
/// use json_object::ObjectBuilder;
/// let obj = ObjectBuilder::new()
///     .set("name", "Rebon402")
///     .set("age", 30i64)
///     .set("active", true)
///     .build();
/// assert_eq!(obj["name"].as_str(), Some("Rebon402"));
/// ```
pub struct ObjectBuilder(HashMap<String, Json>);

impl ObjectBuilder {
    pub fn new() -> Self { ObjectBuilder(HashMap::new()) }

    pub fn set(mut self, key: impl Into<String>, value: impl Into<Json>) -> Self {
        self.0.insert(key.into(), value.into());
        self
    }

    pub fn set_if(self, cond: bool, key: impl Into<String>, value: impl Into<Json>) -> Self {
        if cond { self.set(key, value) } else { self }
    }

    pub fn merge(mut self, other: &Json) -> Self {
        if let Json::Object(m) = other {
            for (k, v) in m { self.0.insert(k.clone(), v.clone()); }
        }
        self
    }

    pub fn build(self) -> Json { Json::Object(self.0) }
}

impl Default for ObjectBuilder {
    fn default() -> Self { Self::new() }
}

/// Fluent builder for JSON arrays.
///
/// ```
/// use json_object::ArrayBuilder;
/// let arr = ArrayBuilder::new()
///     .push(1i64)
///     .push("hello")
///     .push(true)
///     .build();
/// assert_eq!(arr[0].as_i64(), Some(1));
/// ```
pub struct ArrayBuilder(Vec<Json>);

impl ArrayBuilder {
    pub fn new() -> Self { ArrayBuilder(Vec::new()) }

    pub fn push(mut self, value: impl Into<Json>) -> Self {
        self.0.push(value.into());
        self
    }

    pub fn push_if(self, cond: bool, value: impl Into<Json>) -> Self {
        if cond { self.push(value) } else { self }
    }

    pub fn extend(mut self, iter: impl IntoIterator<Item = impl Into<Json>>) -> Self {
        self.0.extend(iter.into_iter().map(Into::into));
        self
    }

    pub fn build(self) -> Json { Json::Array(self.0) }
}

impl Default for ArrayBuilder {
    fn default() -> Self { Self::new() }
}

// ─── Tests ────────────────────────────────────────────────────────────────────

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

    #[test]
    fn test_macro_basic() {
        let v = json!({
            "name": "Rebon402",
            "age": 30i64,
            "active": true,
            "score": 9.5f64,
            "nothing": null,
            "tags": ["rust", "json"]
        });
        assert_eq!(v["name"].as_str(), Some("Rebon402"));
        assert_eq!(v["age"].as_i64(), Some(30));
        assert_eq!(v["active"].as_bool(), Some(true));
        assert_eq!(v["score"].as_f64(), Some(9.5));
        assert!(v["nothing"].is_null());
        assert_eq!(v["tags"][0].as_str(), Some("rust"));
    }

    #[test]
    fn test_parse_roundtrip() {
        let src = r#"{"a":1,"b":true,"c":null,"d":[1,2,3],"e":{"x":9}}"#;
        let parsed = Json::parse(src).unwrap();
        let reserialized = parsed.to_json();
        let reparsed = Json::parse(&reserialized).unwrap();
        assert_eq!(parsed, reparsed);
    }

    #[test]
    fn test_get_path() {
        let v = json!({ "user": { "address": { "city": "Bangkok" } } });
        assert_eq!(v.get_path("user.address.city").unwrap().as_str(), Some("Bangkok"));
    }

    #[test]
    fn test_builder() {
        let obj = ObjectBuilder::new()
            .set("x", 42i64)
            .set("y", "hello")
            .build();
        assert_eq!(obj["x"].as_i64(), Some(42));

        let arr = ArrayBuilder::new()
            .push(1i64).push(2i64).push(3i64)
            .build();
        assert_eq!(arr[1].as_i64(), Some(2));
    }

    #[test]
    fn test_mutation() {
        let mut obj = Json::new_object();
        obj.set("key", "value");
        obj.set("num", 99i64);
        assert_eq!(obj["num"].as_i64(), Some(99));
        obj.remove("key");
        assert!(obj["key"].is_null());
    }

    #[test]
    fn test_pretty_print() {
        let v = json!({"a": 1i64, "b": [1i64, 2i64]});
        let pretty = v.to_pretty("  ");
        assert!(pretty.contains('\n'));
    }

    #[test]
    fn test_unicode_escape() {
        let src = r#"{"emoji": "\u0041BC"}"#; // \u0041 = 'A'
        let v = Json::parse(src).unwrap();
        assert_eq!(v["emoji"].as_str(), Some("ABC"));
    }

    #[test]
    fn test_contains_key() {
        let v = json!({"x": 1i64});
        assert!(v.contains_key("x"));
        assert!(!v.contains_key("y"));
    }

    #[test]
    fn test_merge() {
        let mut a = json!({"x": 1i64});
        let b = json!({"y": 2i64});
        a.merge(&b);
        assert_eq!(a["y"].as_i64(), Some(2));
    }
}