Coverage Report

Created: 2025-07-23 06:16

/src/json/src/value/mod.rs
Line
Count
Source (jump to first uncovered line)
1
//! The Value enum, a loosely typed way of representing any valid JSON value.
2
//!
3
//! # Constructing JSON
4
//!
5
//! Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value`
6
//! objects with very natural JSON syntax.
7
//!
8
//! ```
9
//! use serde_json::json;
10
//!
11
//! fn main() {
12
//!     // The type of `john` is `serde_json::Value`
13
//!     let john = json!({
14
//!         "name": "John Doe",
15
//!         "age": 43,
16
//!         "phones": [
17
//!             "+44 1234567",
18
//!             "+44 2345678"
19
//!         ]
20
//!     });
21
//!
22
//!     println!("first phone number: {}", john["phones"][0]);
23
//!
24
//!     // Convert to a string of JSON and print it out
25
//!     println!("{}", john.to_string());
26
//! }
27
//! ```
28
//!
29
//! The `Value::to_string()` function converts a `serde_json::Value` into a
30
//! `String` of JSON text.
31
//!
32
//! One neat thing about the `json!` macro is that variables and expressions can
33
//! be interpolated directly into the JSON value as you are building it. Serde
34
//! will check at compile time that the value you are interpolating is able to
35
//! be represented as JSON.
36
//!
37
//! ```
38
//! # use serde_json::json;
39
//! #
40
//! # fn random_phone() -> u16 { 0 }
41
//! #
42
//! let full_name = "John Doe";
43
//! let age_last_year = 42;
44
//!
45
//! // The type of `john` is `serde_json::Value`
46
//! let john = json!({
47
//!     "name": full_name,
48
//!     "age": age_last_year + 1,
49
//!     "phones": [
50
//!         format!("+44 {}", random_phone())
51
//!     ]
52
//! });
53
//! ```
54
//!
55
//! A string of JSON data can be parsed into a `serde_json::Value` by the
56
//! [`serde_json::from_str`][from_str] function. There is also
57
//! [`from_slice`][from_slice] for parsing from a byte slice `&[u8]` and
58
//! [`from_reader`][from_reader] for parsing from any `io::Read` like a File or
59
//! a TCP stream.
60
//!
61
//! ```
62
//! use serde_json::{json, Value, Error};
63
//!
64
//! fn untyped_example() -> Result<(), Error> {
65
//!     // Some JSON input data as a &str. Maybe this comes from the user.
66
//!     let data = r#"
67
//!         {
68
//!             "name": "John Doe",
69
//!             "age": 43,
70
//!             "phones": [
71
//!                 "+44 1234567",
72
//!                 "+44 2345678"
73
//!             ]
74
//!         }"#;
75
//!
76
//!     // Parse the string of data into serde_json::Value.
77
//!     let v: Value = serde_json::from_str(data)?;
78
//!
79
//!     // Access parts of the data by indexing with square brackets.
80
//!     println!("Please call {} at the number {}", v["name"], v["phones"][0]);
81
//!
82
//!     Ok(())
83
//! }
84
//! #
85
//! # untyped_example().unwrap();
86
//! ```
87
//!
88
//! [macro]: crate::json
89
//! [from_str]: crate::de::from_str
90
//! [from_slice]: crate::de::from_slice
91
//! [from_reader]: crate::de::from_reader
92
93
use crate::error::Error;
94
use crate::io;
95
use alloc::string::String;
96
use alloc::vec::Vec;
97
use core::fmt::{self, Debug, Display};
98
use core::mem;
99
use core::str;
100
use serde::de::DeserializeOwned;
101
use serde::ser::Serialize;
102
103
pub use self::index::Index;
104
pub use self::ser::Serializer;
105
pub use crate::map::Map;
106
pub use crate::number::Number;
107
108
#[cfg(feature = "raw_value")]
109
#[cfg_attr(docsrs, doc(cfg(feature = "raw_value")))]
110
pub use crate::raw::{to_raw_value, RawValue};
111
112
/// Represents any valid JSON value.
113
///
114
/// See the [`serde_json::value` module documentation](self) for usage examples.
115
#[derive(Clone, Eq, PartialEq, Hash)]
116
pub enum Value {
117
    /// Represents a JSON null value.
118
    ///
119
    /// ```
120
    /// # use serde_json::json;
121
    /// #
122
    /// let v = json!(null);
123
    /// ```
124
    Null,
125
126
    /// Represents a JSON boolean.
127
    ///
128
    /// ```
129
    /// # use serde_json::json;
130
    /// #
131
    /// let v = json!(true);
132
    /// ```
133
    Bool(bool),
134
135
    /// Represents a JSON number, whether integer or floating point.
136
    ///
137
    /// ```
138
    /// # use serde_json::json;
139
    /// #
140
    /// let v = json!(12.5);
141
    /// ```
142
    Number(Number),
143
144
    /// Represents a JSON string.
145
    ///
146
    /// ```
147
    /// # use serde_json::json;
148
    /// #
149
    /// let v = json!("a string");
150
    /// ```
151
    String(String),
152
153
    /// Represents a JSON array.
154
    ///
155
    /// ```
156
    /// # use serde_json::json;
157
    /// #
158
    /// let v = json!(["an", "array"]);
159
    /// ```
160
    Array(Vec<Value>),
161
162
    /// Represents a JSON object.
163
    ///
164
    /// By default the map is backed by a BTreeMap. Enable the `preserve_order`
165
    /// feature of serde_json to use IndexMap instead, which preserves
166
    /// entries in the order they are inserted into the map. In particular, this
167
    /// allows JSON data to be deserialized into a Value and serialized to a
168
    /// string while retaining the order of map keys in the input.
169
    ///
170
    /// ```
171
    /// # use serde_json::json;
172
    /// #
173
    /// let v = json!({ "an": "object" });
174
    /// ```
175
    Object(Map<String, Value>),
176
}
177
178
impl Debug for Value {
179
0
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
180
0
        match self {
181
0
            Value::Null => formatter.write_str("Null"),
182
0
            Value::Bool(boolean) => write!(formatter, "Bool({})", boolean),
183
0
            Value::Number(number) => Debug::fmt(number, formatter),
184
0
            Value::String(string) => write!(formatter, "String({:?})", string),
185
0
            Value::Array(vec) => {
186
0
                tri!(formatter.write_str("Array "));
187
0
                Debug::fmt(vec, formatter)
188
            }
189
0
            Value::Object(map) => {
190
0
                tri!(formatter.write_str("Object "));
191
0
                Debug::fmt(map, formatter)
192
            }
193
        }
194
0
    }
195
}
196
197
impl Display for Value {
198
    /// Display a JSON value as a string.
199
    ///
200
    /// ```
201
    /// # use serde_json::json;
202
    /// #
203
    /// let json = json!({ "city": "London", "street": "10 Downing Street" });
204
    ///
205
    /// // Compact format:
206
    /// //
207
    /// // {"city":"London","street":"10 Downing Street"}
208
    /// let compact = format!("{}", json);
209
    /// assert_eq!(compact,
210
    ///     "{\"city\":\"London\",\"street\":\"10 Downing Street\"}");
211
    ///
212
    /// // Pretty format:
213
    /// //
214
    /// // {
215
    /// //   "city": "London",
216
    /// //   "street": "10 Downing Street"
217
    /// // }
218
    /// let pretty = format!("{:#}", json);
219
    /// assert_eq!(pretty,
220
    ///     "{\n  \"city\": \"London\",\n  \"street\": \"10 Downing Street\"\n}");
221
    /// ```
222
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
223
        struct WriterFormatter<'a, 'b: 'a> {
224
            inner: &'a mut fmt::Formatter<'b>,
225
        }
226
227
        impl<'a, 'b> io::Write for WriterFormatter<'a, 'b> {
228
0
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
229
0
                // Safety: the serializer below only emits valid utf8 when using
230
0
                // the default formatter.
231
0
                let s = unsafe { str::from_utf8_unchecked(buf) };
232
0
                tri!(self.inner.write_str(s).map_err(io_error));
233
0
                Ok(buf.len())
234
0
            }
235
236
0
            fn flush(&mut self) -> io::Result<()> {
237
0
                Ok(())
238
0
            }
239
        }
240
241
0
        fn io_error(_: fmt::Error) -> io::Error {
242
0
            // Error value does not matter because Display impl just maps it
243
0
            // back to fmt::Error.
244
0
            io::Error::new(io::ErrorKind::Other, "fmt error")
245
0
        }
246
247
0
        let alternate = f.alternate();
248
0
        let mut wr = WriterFormatter { inner: f };
249
0
        if alternate {
250
            // {:#}
251
0
            super::ser::to_writer_pretty(&mut wr, self).map_err(|_| fmt::Error)
252
        } else {
253
            // {}
254
0
            super::ser::to_writer(&mut wr, self).map_err(|_| fmt::Error)
255
        }
256
0
    }
257
}
258
259
0
fn parse_index(s: &str) -> Option<usize> {
260
0
    if s.starts_with('+') || (s.starts_with('0') && s.len() != 1) {
261
0
        return None;
262
0
    }
263
0
    s.parse().ok()
264
0
}
265
266
impl Value {
267
    /// Index into a JSON array or map. A string index can be used to access a
268
    /// value in a map, and a usize index can be used to access an element of an
269
    /// array.
270
    ///
271
    /// Returns `None` if the type of `self` does not match the type of the
272
    /// index, for example if the index is a string and `self` is an array or a
273
    /// number. Also returns `None` if the given key does not exist in the map
274
    /// or the given index is not within the bounds of the array.
275
    ///
276
    /// ```
277
    /// # use serde_json::json;
278
    /// #
279
    /// let object = json!({ "A": 65, "B": 66, "C": 67 });
280
    /// assert_eq!(*object.get("A").unwrap(), json!(65));
281
    ///
282
    /// let array = json!([ "A", "B", "C" ]);
283
    /// assert_eq!(*array.get(2).unwrap(), json!("C"));
284
    ///
285
    /// assert_eq!(array.get("A"), None);
286
    /// ```
287
    ///
288
    /// Square brackets can also be used to index into a value in a more concise
289
    /// way. This returns `Value::Null` in cases where `get` would have returned
290
    /// `None`.
291
    ///
292
    /// ```
293
    /// # use serde_json::json;
294
    /// #
295
    /// let object = json!({
296
    ///     "A": ["a", "á", "à"],
297
    ///     "B": ["b", "b́"],
298
    ///     "C": ["c", "ć", "ć̣", "ḉ"],
299
    /// });
300
    /// assert_eq!(object["B"][0], json!("b"));
301
    ///
302
    /// assert_eq!(object["D"], json!(null));
303
    /// assert_eq!(object[0]["x"]["y"]["z"], json!(null));
304
    /// ```
305
0
    pub fn get<I: Index>(&self, index: I) -> Option<&Value> {
306
0
        index.index_into(self)
307
0
    }
308
309
    /// Mutably index into a JSON array or map. A string index can be used to
310
    /// access a value in a map, and a usize index can be used to access an
311
    /// element of an array.
312
    ///
313
    /// Returns `None` if the type of `self` does not match the type of the
314
    /// index, for example if the index is a string and `self` is an array or a
315
    /// number. Also returns `None` if the given key does not exist in the map
316
    /// or the given index is not within the bounds of the array.
317
    ///
318
    /// ```
319
    /// # use serde_json::json;
320
    /// #
321
    /// let mut object = json!({ "A": 65, "B": 66, "C": 67 });
322
    /// *object.get_mut("A").unwrap() = json!(69);
323
    ///
324
    /// let mut array = json!([ "A", "B", "C" ]);
325
    /// *array.get_mut(2).unwrap() = json!("D");
326
    /// ```
327
0
    pub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut Value> {
328
0
        index.index_into_mut(self)
329
0
    }
330
331
    /// Returns true if the `Value` is an Object. Returns false otherwise.
332
    ///
333
    /// For any Value on which `is_object` returns true, `as_object` and
334
    /// `as_object_mut` are guaranteed to return the map representation of the
335
    /// object.
336
    ///
337
    /// ```
338
    /// # use serde_json::json;
339
    /// #
340
    /// let obj = json!({ "a": { "nested": true }, "b": ["an", "array"] });
341
    ///
342
    /// assert!(obj.is_object());
343
    /// assert!(obj["a"].is_object());
344
    ///
345
    /// // array, not an object
346
    /// assert!(!obj["b"].is_object());
347
    /// ```
348
0
    pub fn is_object(&self) -> bool {
349
0
        self.as_object().is_some()
350
0
    }
351
352
    /// If the `Value` is an Object, returns the associated Map. Returns None
353
    /// otherwise.
354
    ///
355
    /// ```
356
    /// # use serde_json::json;
357
    /// #
358
    /// let v = json!({ "a": { "nested": true }, "b": ["an", "array"] });
359
    ///
360
    /// // The length of `{"nested": true}` is 1 entry.
361
    /// assert_eq!(v["a"].as_object().unwrap().len(), 1);
362
    ///
363
    /// // The array `["an", "array"]` is not an object.
364
    /// assert_eq!(v["b"].as_object(), None);
365
    /// ```
366
0
    pub fn as_object(&self) -> Option<&Map<String, Value>> {
367
0
        match self {
368
0
            Value::Object(map) => Some(map),
369
0
            _ => None,
370
        }
371
0
    }
372
373
    /// If the `Value` is an Object, returns the associated mutable Map.
374
    /// Returns None otherwise.
375
    ///
376
    /// ```
377
    /// # use serde_json::json;
378
    /// #
379
    /// let mut v = json!({ "a": { "nested": true } });
380
    ///
381
    /// v["a"].as_object_mut().unwrap().clear();
382
    /// assert_eq!(v, json!({ "a": {} }));
383
    /// ```
384
0
    pub fn as_object_mut(&mut self) -> Option<&mut Map<String, Value>> {
385
0
        match self {
386
0
            Value::Object(map) => Some(map),
387
0
            _ => None,
388
        }
389
0
    }
390
391
    /// Returns true if the `Value` is an Array. Returns false otherwise.
392
    ///
393
    /// For any Value on which `is_array` returns true, `as_array` and
394
    /// `as_array_mut` are guaranteed to return the vector representing the
395
    /// array.
396
    ///
397
    /// ```
398
    /// # use serde_json::json;
399
    /// #
400
    /// let obj = json!({ "a": ["an", "array"], "b": { "an": "object" } });
401
    ///
402
    /// assert!(obj["a"].is_array());
403
    ///
404
    /// // an object, not an array
405
    /// assert!(!obj["b"].is_array());
406
    /// ```
407
0
    pub fn is_array(&self) -> bool {
408
0
        self.as_array().is_some()
409
0
    }
410
411
    /// If the `Value` is an Array, returns the associated vector. Returns None
412
    /// otherwise.
413
    ///
414
    /// ```
415
    /// # use serde_json::json;
416
    /// #
417
    /// let v = json!({ "a": ["an", "array"], "b": { "an": "object" } });
418
    ///
419
    /// // The length of `["an", "array"]` is 2 elements.
420
    /// assert_eq!(v["a"].as_array().unwrap().len(), 2);
421
    ///
422
    /// // The object `{"an": "object"}` is not an array.
423
    /// assert_eq!(v["b"].as_array(), None);
424
    /// ```
425
0
    pub fn as_array(&self) -> Option<&Vec<Value>> {
426
0
        match self {
427
0
            Value::Array(array) => Some(array),
428
0
            _ => None,
429
        }
430
0
    }
431
432
    /// If the `Value` is an Array, returns the associated mutable vector.
433
    /// Returns None otherwise.
434
    ///
435
    /// ```
436
    /// # use serde_json::json;
437
    /// #
438
    /// let mut v = json!({ "a": ["an", "array"] });
439
    ///
440
    /// v["a"].as_array_mut().unwrap().clear();
441
    /// assert_eq!(v, json!({ "a": [] }));
442
    /// ```
443
0
    pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> {
444
0
        match self {
445
0
            Value::Array(list) => Some(list),
446
0
            _ => None,
447
        }
448
0
    }
449
450
    /// Returns true if the `Value` is a String. Returns false otherwise.
451
    ///
452
    /// For any Value on which `is_string` returns true, `as_str` is guaranteed
453
    /// to return the string slice.
454
    ///
455
    /// ```
456
    /// # use serde_json::json;
457
    /// #
458
    /// let v = json!({ "a": "some string", "b": false });
459
    ///
460
    /// assert!(v["a"].is_string());
461
    ///
462
    /// // The boolean `false` is not a string.
463
    /// assert!(!v["b"].is_string());
464
    /// ```
465
0
    pub fn is_string(&self) -> bool {
466
0
        self.as_str().is_some()
467
0
    }
468
469
    /// If the `Value` is a String, returns the associated str. Returns None
470
    /// otherwise.
471
    ///
472
    /// ```
473
    /// # use serde_json::json;
474
    /// #
475
    /// let v = json!({ "a": "some string", "b": false });
476
    ///
477
    /// assert_eq!(v["a"].as_str(), Some("some string"));
478
    ///
479
    /// // The boolean `false` is not a string.
480
    /// assert_eq!(v["b"].as_str(), None);
481
    ///
482
    /// // JSON values are printed in JSON representation, so strings are in quotes.
483
    /// //
484
    /// //    The value is: "some string"
485
    /// println!("The value is: {}", v["a"]);
486
    ///
487
    /// // Rust strings are printed without quotes.
488
    /// //
489
    /// //    The value is: some string
490
    /// println!("The value is: {}", v["a"].as_str().unwrap());
491
    /// ```
492
0
    pub fn as_str(&self) -> Option<&str> {
493
0
        match self {
494
0
            Value::String(s) => Some(s),
495
0
            _ => None,
496
        }
497
0
    }
498
499
    /// Returns true if the `Value` is a Number. Returns false otherwise.
500
    ///
501
    /// ```
502
    /// # use serde_json::json;
503
    /// #
504
    /// let v = json!({ "a": 1, "b": "2" });
505
    ///
506
    /// assert!(v["a"].is_number());
507
    ///
508
    /// // The string `"2"` is a string, not a number.
509
    /// assert!(!v["b"].is_number());
510
    /// ```
511
0
    pub fn is_number(&self) -> bool {
512
0
        match *self {
513
0
            Value::Number(_) => true,
514
0
            _ => false,
515
        }
516
0
    }
517
518
    /// If the `Value` is a Number, returns the associated [`Number`]. Returns
519
    /// None otherwise.
520
    ///
521
    /// ```
522
    /// # use serde_json::{json, Number};
523
    /// #
524
    /// let v = json!({ "a": 1, "b": 2.2, "c": -3, "d": "4" });
525
    ///
526
    /// assert_eq!(v["a"].as_number(), Some(&Number::from(1u64)));
527
    /// assert_eq!(v["b"].as_number(), Some(&Number::from_f64(2.2).unwrap()));
528
    /// assert_eq!(v["c"].as_number(), Some(&Number::from(-3i64)));
529
    ///
530
    /// // The string `"4"` is not a number.
531
    /// assert_eq!(v["d"].as_number(), None);
532
    /// ```
533
0
    pub fn as_number(&self) -> Option<&Number> {
534
0
        match self {
535
0
            Value::Number(number) => Some(number),
536
0
            _ => None,
537
        }
538
0
    }
539
540
    /// Returns true if the `Value` is an integer between `i64::MIN` and
541
    /// `i64::MAX`.
542
    ///
543
    /// For any Value on which `is_i64` returns true, `as_i64` is guaranteed to
544
    /// return the integer value.
545
    ///
546
    /// ```
547
    /// # use serde_json::json;
548
    /// #
549
    /// let big = i64::max_value() as u64 + 10;
550
    /// let v = json!({ "a": 64, "b": big, "c": 256.0 });
551
    ///
552
    /// assert!(v["a"].is_i64());
553
    ///
554
    /// // Greater than i64::MAX.
555
    /// assert!(!v["b"].is_i64());
556
    ///
557
    /// // Numbers with a decimal point are not considered integers.
558
    /// assert!(!v["c"].is_i64());
559
    /// ```
560
0
    pub fn is_i64(&self) -> bool {
561
0
        match self {
562
0
            Value::Number(n) => n.is_i64(),
563
0
            _ => false,
564
        }
565
0
    }
566
567
    /// Returns true if the `Value` is an integer between zero and `u64::MAX`.
568
    ///
569
    /// For any Value on which `is_u64` returns true, `as_u64` is guaranteed to
570
    /// return the integer value.
571
    ///
572
    /// ```
573
    /// # use serde_json::json;
574
    /// #
575
    /// let v = json!({ "a": 64, "b": -64, "c": 256.0 });
576
    ///
577
    /// assert!(v["a"].is_u64());
578
    ///
579
    /// // Negative integer.
580
    /// assert!(!v["b"].is_u64());
581
    ///
582
    /// // Numbers with a decimal point are not considered integers.
583
    /// assert!(!v["c"].is_u64());
584
    /// ```
585
0
    pub fn is_u64(&self) -> bool {
586
0
        match self {
587
0
            Value::Number(n) => n.is_u64(),
588
0
            _ => false,
589
        }
590
0
    }
591
592
    /// Returns true if the `Value` is a number that can be represented by f64.
593
    ///
594
    /// For any Value on which `is_f64` returns true, `as_f64` is guaranteed to
595
    /// return the floating point value.
596
    ///
597
    /// Currently this function returns true if and only if both `is_i64` and
598
    /// `is_u64` return false but this is not a guarantee in the future.
599
    ///
600
    /// ```
601
    /// # use serde_json::json;
602
    /// #
603
    /// let v = json!({ "a": 256.0, "b": 64, "c": -64 });
604
    ///
605
    /// assert!(v["a"].is_f64());
606
    ///
607
    /// // Integers.
608
    /// assert!(!v["b"].is_f64());
609
    /// assert!(!v["c"].is_f64());
610
    /// ```
611
0
    pub fn is_f64(&self) -> bool {
612
0
        match self {
613
0
            Value::Number(n) => n.is_f64(),
614
0
            _ => false,
615
        }
616
0
    }
617
618
    /// If the `Value` is an integer, represent it as i64 if possible. Returns
619
    /// None otherwise.
620
    ///
621
    /// ```
622
    /// # use serde_json::json;
623
    /// #
624
    /// let big = i64::max_value() as u64 + 10;
625
    /// let v = json!({ "a": 64, "b": big, "c": 256.0 });
626
    ///
627
    /// assert_eq!(v["a"].as_i64(), Some(64));
628
    /// assert_eq!(v["b"].as_i64(), None);
629
    /// assert_eq!(v["c"].as_i64(), None);
630
    /// ```
631
0
    pub fn as_i64(&self) -> Option<i64> {
632
0
        match self {
633
0
            Value::Number(n) => n.as_i64(),
634
0
            _ => None,
635
        }
636
0
    }
637
638
    /// If the `Value` is an integer, represent it as u64 if possible. Returns
639
    /// None otherwise.
640
    ///
641
    /// ```
642
    /// # use serde_json::json;
643
    /// #
644
    /// let v = json!({ "a": 64, "b": -64, "c": 256.0 });
645
    ///
646
    /// assert_eq!(v["a"].as_u64(), Some(64));
647
    /// assert_eq!(v["b"].as_u64(), None);
648
    /// assert_eq!(v["c"].as_u64(), None);
649
    /// ```
650
0
    pub fn as_u64(&self) -> Option<u64> {
651
0
        match self {
652
0
            Value::Number(n) => n.as_u64(),
653
0
            _ => None,
654
        }
655
0
    }
656
657
    /// If the `Value` is a number, represent it as f64 if possible. Returns
658
    /// None otherwise.
659
    ///
660
    /// ```
661
    /// # use serde_json::json;
662
    /// #
663
    /// let v = json!({ "a": 256.0, "b": 64, "c": -64 });
664
    ///
665
    /// assert_eq!(v["a"].as_f64(), Some(256.0));
666
    /// assert_eq!(v["b"].as_f64(), Some(64.0));
667
    /// assert_eq!(v["c"].as_f64(), Some(-64.0));
668
    /// ```
669
0
    pub fn as_f64(&self) -> Option<f64> {
670
0
        match self {
671
0
            Value::Number(n) => n.as_f64(),
672
0
            _ => None,
673
        }
674
0
    }
675
676
    /// Returns true if the `Value` is a Boolean. Returns false otherwise.
677
    ///
678
    /// For any Value on which `is_boolean` returns true, `as_bool` is
679
    /// guaranteed to return the boolean value.
680
    ///
681
    /// ```
682
    /// # use serde_json::json;
683
    /// #
684
    /// let v = json!({ "a": false, "b": "false" });
685
    ///
686
    /// assert!(v["a"].is_boolean());
687
    ///
688
    /// // The string `"false"` is a string, not a boolean.
689
    /// assert!(!v["b"].is_boolean());
690
    /// ```
691
0
    pub fn is_boolean(&self) -> bool {
692
0
        self.as_bool().is_some()
693
0
    }
694
695
    /// If the `Value` is a Boolean, returns the associated bool. Returns None
696
    /// otherwise.
697
    ///
698
    /// ```
699
    /// # use serde_json::json;
700
    /// #
701
    /// let v = json!({ "a": false, "b": "false" });
702
    ///
703
    /// assert_eq!(v["a"].as_bool(), Some(false));
704
    ///
705
    /// // The string `"false"` is a string, not a boolean.
706
    /// assert_eq!(v["b"].as_bool(), None);
707
    /// ```
708
0
    pub fn as_bool(&self) -> Option<bool> {
709
0
        match *self {
710
0
            Value::Bool(b) => Some(b),
711
0
            _ => None,
712
        }
713
0
    }
714
715
    /// Returns true if the `Value` is a Null. Returns false otherwise.
716
    ///
717
    /// For any Value on which `is_null` returns true, `as_null` is guaranteed
718
    /// to return `Some(())`.
719
    ///
720
    /// ```
721
    /// # use serde_json::json;
722
    /// #
723
    /// let v = json!({ "a": null, "b": false });
724
    ///
725
    /// assert!(v["a"].is_null());
726
    ///
727
    /// // The boolean `false` is not null.
728
    /// assert!(!v["b"].is_null());
729
    /// ```
730
0
    pub fn is_null(&self) -> bool {
731
0
        self.as_null().is_some()
732
0
    }
733
734
    /// If the `Value` is a Null, returns (). Returns None otherwise.
735
    ///
736
    /// ```
737
    /// # use serde_json::json;
738
    /// #
739
    /// let v = json!({ "a": null, "b": false });
740
    ///
741
    /// assert_eq!(v["a"].as_null(), Some(()));
742
    ///
743
    /// // The boolean `false` is not null.
744
    /// assert_eq!(v["b"].as_null(), None);
745
    /// ```
746
0
    pub fn as_null(&self) -> Option<()> {
747
0
        match *self {
748
0
            Value::Null => Some(()),
749
0
            _ => None,
750
        }
751
0
    }
752
753
    /// Looks up a value by a JSON Pointer.
754
    ///
755
    /// JSON Pointer defines a string syntax for identifying a specific value
756
    /// within a JavaScript Object Notation (JSON) document.
757
    ///
758
    /// A Pointer is a Unicode string with the reference tokens separated by `/`.
759
    /// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The
760
    /// addressed value is returned and if there is no such value `None` is
761
    /// returned.
762
    ///
763
    /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901).
764
    ///
765
    /// # Examples
766
    ///
767
    /// ```
768
    /// # use serde_json::json;
769
    /// #
770
    /// let data = json!({
771
    ///     "x": {
772
    ///         "y": ["z", "zz"]
773
    ///     }
774
    /// });
775
    ///
776
    /// assert_eq!(data.pointer("/x/y/1").unwrap(), &json!("zz"));
777
    /// assert_eq!(data.pointer("/a/b/c"), None);
778
    /// ```
779
0
    pub fn pointer(&self, pointer: &str) -> Option<&Value> {
780
0
        if pointer.is_empty() {
781
0
            return Some(self);
782
0
        }
783
0
        if !pointer.starts_with('/') {
784
0
            return None;
785
0
        }
786
0
        pointer
787
0
            .split('/')
788
0
            .skip(1)
789
0
            .map(|x| x.replace("~1", "/").replace("~0", "~"))
790
0
            .try_fold(self, |target, token| match target {
791
0
                Value::Object(map) => map.get(&token),
792
0
                Value::Array(list) => parse_index(&token).and_then(|x| list.get(x)),
793
0
                _ => None,
794
0
            })
795
0
    }
796
797
    /// Looks up a value by a JSON Pointer and returns a mutable reference to
798
    /// that value.
799
    ///
800
    /// JSON Pointer defines a string syntax for identifying a specific value
801
    /// within a JavaScript Object Notation (JSON) document.
802
    ///
803
    /// A Pointer is a Unicode string with the reference tokens separated by `/`.
804
    /// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The
805
    /// addressed value is returned and if there is no such value `None` is
806
    /// returned.
807
    ///
808
    /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901).
809
    ///
810
    /// # Example of Use
811
    ///
812
    /// ```
813
    /// use serde_json::Value;
814
    ///
815
    /// fn main() {
816
    ///     let s = r#"{"x": 1.0, "y": 2.0}"#;
817
    ///     let mut value: Value = serde_json::from_str(s).unwrap();
818
    ///
819
    ///     // Check value using read-only pointer
820
    ///     assert_eq!(value.pointer("/x"), Some(&1.0.into()));
821
    ///     // Change value with direct assignment
822
    ///     *value.pointer_mut("/x").unwrap() = 1.5.into();
823
    ///     // Check that new value was written
824
    ///     assert_eq!(value.pointer("/x"), Some(&1.5.into()));
825
    ///     // Or change the value only if it exists
826
    ///     value.pointer_mut("/x").map(|v| *v = 1.5.into());
827
    ///
828
    ///     // "Steal" ownership of a value. Can replace with any valid Value.
829
    ///     let old_x = value.pointer_mut("/x").map(Value::take).unwrap();
830
    ///     assert_eq!(old_x, 1.5);
831
    ///     assert_eq!(value.pointer("/x").unwrap(), &Value::Null);
832
    /// }
833
    /// ```
834
0
    pub fn pointer_mut(&mut self, pointer: &str) -> Option<&mut Value> {
835
0
        if pointer.is_empty() {
836
0
            return Some(self);
837
0
        }
838
0
        if !pointer.starts_with('/') {
839
0
            return None;
840
0
        }
841
0
        pointer
842
0
            .split('/')
843
0
            .skip(1)
844
0
            .map(|x| x.replace("~1", "/").replace("~0", "~"))
845
0
            .try_fold(self, |target, token| match target {
846
0
                Value::Object(map) => map.get_mut(&token),
847
0
                Value::Array(list) => parse_index(&token).and_then(move |x| list.get_mut(x)),
848
0
                _ => None,
849
0
            })
850
0
    }
851
852
    /// Takes the value out of the `Value`, leaving a `Null` in its place.
853
    ///
854
    /// ```
855
    /// # use serde_json::json;
856
    /// #
857
    /// let mut v = json!({ "x": "y" });
858
    /// assert_eq!(v["x"].take(), json!("y"));
859
    /// assert_eq!(v, json!({ "x": null }));
860
    /// ```
861
0
    pub fn take(&mut self) -> Value {
862
0
        mem::replace(self, Value::Null)
863
0
    }
864
865
    /// Reorders the entries of all `Value::Object` nested within this JSON
866
    /// value according to `str`'s usual ordering.
867
    ///
868
    /// If serde_json's "preserve_order" feature is not enabled, this method
869
    /// does no work because all JSON maps are always kept in a sorted state.
870
    ///
871
    /// If serde_json's "preserve_order" feature is enabled, this method
872
    /// destroys the original source order or insertion order of the JSON
873
    /// objects in favor of an alphanumerical order that matches how a BTreeMap
874
    /// with the same contents would be ordered.
875
0
    pub fn sort_all_objects(&mut self) {
876
0
        #[cfg(feature = "preserve_order")]
877
0
        {
878
0
            match self {
879
0
                Value::Object(map) => {
880
0
                    map.sort_keys();
881
0
                    map.values_mut().for_each(Value::sort_all_objects);
882
0
                }
883
0
                Value::Array(list) => {
884
0
                    list.iter_mut().for_each(Value::sort_all_objects);
885
0
                }
886
0
                _ => {}
887
0
            }
888
0
        }
889
0
    }
890
}
891
892
/// The default value is `Value::Null`.
893
///
894
/// This is useful for handling omitted `Value` fields when deserializing.
895
///
896
/// # Examples
897
///
898
/// ```
899
/// # use serde::Deserialize;
900
/// use serde_json::Value;
901
///
902
/// #[derive(Deserialize)]
903
/// struct Settings {
904
///     level: i32,
905
///     #[serde(default)]
906
///     extras: Value,
907
/// }
908
///
909
/// # fn try_main() -> Result<(), serde_json::Error> {
910
/// let data = r#" { "level": 42 } "#;
911
/// let s: Settings = serde_json::from_str(data)?;
912
///
913
/// assert_eq!(s.level, 42);
914
/// assert_eq!(s.extras, Value::Null);
915
/// #
916
/// #     Ok(())
917
/// # }
918
/// #
919
/// # try_main().unwrap()
920
/// ```
921
impl Default for Value {
922
0
    fn default() -> Value {
923
0
        Value::Null
924
0
    }
925
}
926
927
mod de;
928
mod from;
929
mod index;
930
mod partial_eq;
931
mod ser;
932
933
/// Convert a `T` into `serde_json::Value` which is an enum that can represent
934
/// any valid JSON data.
935
///
936
/// # Example
937
///
938
/// ```
939
/// use serde::Serialize;
940
/// use serde_json::json;
941
/// use std::error::Error;
942
///
943
/// #[derive(Serialize)]
944
/// struct User {
945
///     fingerprint: String,
946
///     location: String,
947
/// }
948
///
949
/// fn compare_json_values() -> Result<(), Box<dyn Error>> {
950
///     let u = User {
951
///         fingerprint: "0xF9BA143B95FF6D82".to_owned(),
952
///         location: "Menlo Park, CA".to_owned(),
953
///     };
954
///
955
///     // The type of `expected` is `serde_json::Value`
956
///     let expected = json!({
957
///         "fingerprint": "0xF9BA143B95FF6D82",
958
///         "location": "Menlo Park, CA",
959
///     });
960
///
961
///     let v = serde_json::to_value(u).unwrap();
962
///     assert_eq!(v, expected);
963
///
964
///     Ok(())
965
/// }
966
/// #
967
/// # compare_json_values().unwrap();
968
/// ```
969
///
970
/// # Errors
971
///
972
/// This conversion can fail if `T`'s implementation of `Serialize` decides to
973
/// fail, or if `T` contains a map with non-string keys.
974
///
975
/// ```
976
/// use std::collections::BTreeMap;
977
///
978
/// fn main() {
979
///     // The keys in this map are vectors, not strings.
980
///     let mut map = BTreeMap::new();
981
///     map.insert(vec![32, 64], "x86");
982
///
983
///     println!("{}", serde_json::to_value(map).unwrap_err());
984
/// }
985
/// ```
986
// Taking by value is more friendly to iterator adapters, option and result
987
// consumers, etc. See https://github.com/serde-rs/json/pull/149.
988
0
pub fn to_value<T>(value: T) -> Result<Value, Error>
989
0
where
990
0
    T: Serialize,
991
0
{
992
0
    value.serialize(Serializer)
993
0
}
994
995
/// Interpret a `serde_json::Value` as an instance of type `T`.
996
///
997
/// # Example
998
///
999
/// ```
1000
/// use serde::Deserialize;
1001
/// use serde_json::json;
1002
///
1003
/// #[derive(Deserialize, Debug)]
1004
/// struct User {
1005
///     fingerprint: String,
1006
///     location: String,
1007
/// }
1008
///
1009
/// fn main() {
1010
///     // The type of `j` is `serde_json::Value`
1011
///     let j = json!({
1012
///         "fingerprint": "0xF9BA143B95FF6D82",
1013
///         "location": "Menlo Park, CA"
1014
///     });
1015
///
1016
///     let u: User = serde_json::from_value(j).unwrap();
1017
///     println!("{:#?}", u);
1018
/// }
1019
/// ```
1020
///
1021
/// # Errors
1022
///
1023
/// This conversion can fail if the structure of the Value does not match the
1024
/// structure expected by `T`, for example if `T` is a struct type but the Value
1025
/// contains something other than a JSON map. It can also fail if the structure
1026
/// is correct but `T`'s implementation of `Deserialize` decides that something
1027
/// is wrong with the data, for example required struct fields are missing from
1028
/// the JSON map or some number is too big to fit in the expected primitive
1029
/// type.
1030
0
pub fn from_value<T>(value: Value) -> Result<T, Error>
1031
0
where
1032
0
    T: DeserializeOwned,
1033
0
{
1034
0
    T::deserialize(value)
1035
0
}