Skip to main content

serde_json/value/
mod.rs

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
93use crate::error::Error;
94use crate::io;
95use alloc::string::String;
96use alloc::vec::Vec;
97use core::fmt::{self, Debug, Display};
98use core::mem;
99use core::str;
100use serde::de::DeserializeOwned;
101use serde::ser::Serialize;
102
103pub use self::index::Index;
104pub use self::ser::Serializer;
105pub use crate::map::Map;
106pub use crate::number::Number;
107
108#[cfg(feature = "raw_value")]
109#[cfg_attr(docsrs, doc(cfg(feature = "raw_value")))]
110pub 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(#[automatically_derived]
impl ::core::clone::Clone for Value {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::Null => Value::Null,
            Self::Bool(__self_0) =>
                Value::Bool(::core::clone::Clone::clone(__self_0)),
            Self::Number(__self_0) =>
                Value::Number(::core::clone::Clone::clone(__self_0)),
            Self::String(__self_0) =>
                Value::String(::core::clone::Clone::clone(__self_0)),
            Self::Array(__self_0) =>
                Value::Array(::core::clone::Clone::clone(__self_0)),
            Self::Object(__self_0) =>
                Value::Object(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, #[automatically_derived]
impl ::core::cmp::Eq for Value {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<bool>;
        let _: ::core::cmp::AssertParamIsEq<Number>;
        let _: ::core::cmp::AssertParamIsEq<String>;
        let _: ::core::cmp::AssertParamIsEq<Vec<Value>>;
        let _: ::core::cmp::AssertParamIsEq<Map<String, Value>>;
    }
}Eq, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for Value { }
#[automatically_derived]
impl ::core::cmp::PartialEq for Value {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Bool(__self_0), Self::Bool(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Number(__self_0), Self::Number(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::String(__self_0), Self::String(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Array(__self_0), Self::Array(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Object(__self_0), Self::Object(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::hash::Hash for Value {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            state);
        match self {
            Self::Bool(__self_0) => ::core::hash::Hash::hash(__self_0, state),
            Self::Number(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            Self::String(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            Self::Array(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            Self::Object(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            _ => {}
        }
    }
}Hash)]
116pub 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
178impl Debug for Value {
179    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
180        match self {
181            Value::Null => formatter.write_str("Null"),
182            Value::Bool(boolean) => formatter.write_fmt(format_args!("Bool({0})", boolean))write!(formatter, "Bool({})", boolean),
183            Value::Number(number) => Debug::fmt(number, formatter),
184            Value::String(string) => formatter.write_fmt(format_args!("String({0:?})", string))write!(formatter, "String({:?})", string),
185            Value::Array(vec) => {
186                match formatter.write_str("Array ") {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(formatter.write_str("Array "));
187                Debug::fmt(vec, formatter)
188            }
189            Value::Object(map) => {
190                match formatter.write_str("Object ") {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(formatter.write_str("Object "));
191                Debug::fmt(map, formatter)
192            }
193        }
194    }
195}
196
197impl 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    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            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
229                // Safety: the serializer below only emits valid utf8 when using
230                // the default formatter.
231                let s = unsafe { str::from_utf8_unchecked(buf) };
232                match self.inner.write_str(s).map_err(io_error) {
    core::result::Result::Ok(val) => val,
    core::result::Result::Err(err) => return core::result::Result::Err(err),
};tri!(self.inner.write_str(s).map_err(io_error));
233                Ok(buf.len())
234            }
235
236            fn flush(&mut self) -> io::Result<()> {
237                Ok(())
238            }
239        }
240
241        // `io::Error::other` does not exist on the no_std shim (src/io/core.rs),
242        // which only has `Error::new(kind, msg)`; clippy's MSRV-gated
243        // io_other_error lint cannot see that.
244        #[allow(clippy::io_other_error)]
245        fn io_error(_: fmt::Error) -> io::Error {
246            // Error value does not matter because Display impl just maps it
247            // back to fmt::Error.
248            io::Error::new(io::ErrorKind::Other, "fmt error")
249        }
250
251        let alternate = f.alternate();
252        let mut wr = WriterFormatter { inner: f };
253        if alternate {
254            // {:#}
255            super::ser::to_writer_pretty(&mut wr, self).map_err(|_| fmt::Error)
256        } else {
257            // {}
258            super::ser::to_writer(&mut wr, self).map_err(|_| fmt::Error)
259        }
260    }
261}
262
263fn parse_index(s: &str) -> Option<usize> {
264    if s.starts_with('+') || (s.starts_with('0') && s.len() != 1) {
265        return None;
266    }
267    s.parse().ok()
268}
269
270impl Value {
271    /// Index into a JSON array or map. A string index can be used to access a
272    /// value in a map, and a usize index can be used to access an element of an
273    /// array.
274    ///
275    /// Returns `None` if the type of `self` does not match the type of the
276    /// index, for example if the index is a string and `self` is an array or a
277    /// number. Also returns `None` if the given key does not exist in the map
278    /// or the given index is not within the bounds of the array.
279    ///
280    /// ```
281    /// # use serde_json::json;
282    /// #
283    /// let object = json!({ "A": 65, "B": 66, "C": 67 });
284    /// assert_eq!(*object.get("A").unwrap(), json!(65));
285    ///
286    /// let array = json!([ "A", "B", "C" ]);
287    /// assert_eq!(*array.get(2).unwrap(), json!("C"));
288    ///
289    /// assert_eq!(array.get("A"), None);
290    /// ```
291    ///
292    /// Square brackets can also be used to index into a value in a more concise
293    /// way. This returns `Value::Null` in cases where `get` would have returned
294    /// `None`.
295    ///
296    /// ```
297    /// # use serde_json::json;
298    /// #
299    /// let object = json!({
300    ///     "A": ["a", "á", "à"],
301    ///     "B": ["b", "b́"],
302    ///     "C": ["c", "ć", "ć̣", "ḉ"],
303    /// });
304    /// assert_eq!(object["B"][0], json!("b"));
305    ///
306    /// assert_eq!(object["D"], json!(null));
307    /// assert_eq!(object[0]["x"]["y"]["z"], json!(null));
308    /// ```
309    pub fn get<I: Index>(&self, index: I) -> Option<&Value> {
310        index.index_into(self)
311    }
312
313    /// Mutably index into a JSON array or map. A string index can be used to
314    /// access a value in a map, and a usize index can be used to access an
315    /// element of an array.
316    ///
317    /// Returns `None` if the type of `self` does not match the type of the
318    /// index, for example if the index is a string and `self` is an array or a
319    /// number. Also returns `None` if the given key does not exist in the map
320    /// or the given index is not within the bounds of the array.
321    ///
322    /// ```
323    /// # use serde_json::json;
324    /// #
325    /// let mut object = json!({ "A": 65, "B": 66, "C": 67 });
326    /// *object.get_mut("A").unwrap() = json!(69);
327    ///
328    /// let mut array = json!([ "A", "B", "C" ]);
329    /// *array.get_mut(2).unwrap() = json!("D");
330    /// ```
331    pub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut Value> {
332        index.index_into_mut(self)
333    }
334
335    /// Returns true if the `Value` is an Object. Returns false otherwise.
336    ///
337    /// For any Value on which `is_object` returns true, `as_object` and
338    /// `as_object_mut` are guaranteed to return the map representation of the
339    /// object.
340    ///
341    /// ```
342    /// # use serde_json::json;
343    /// #
344    /// let obj = json!({ "a": { "nested": true }, "b": ["an", "array"] });
345    ///
346    /// assert!(obj.is_object());
347    /// assert!(obj["a"].is_object());
348    ///
349    /// // array, not an object
350    /// assert!(!obj["b"].is_object());
351    /// ```
352    pub fn is_object(&self) -> bool {
353        self.as_object().is_some()
354    }
355
356    /// If the `Value` is an Object, returns the associated Map. Returns None
357    /// otherwise.
358    ///
359    /// ```
360    /// # use serde_json::json;
361    /// #
362    /// let v = json!({ "a": { "nested": true }, "b": ["an", "array"] });
363    ///
364    /// // The length of `{"nested": true}` is 1 entry.
365    /// assert_eq!(v["a"].as_object().unwrap().len(), 1);
366    ///
367    /// // The array `["an", "array"]` is not an object.
368    /// assert_eq!(v["b"].as_object(), None);
369    /// ```
370    pub fn as_object(&self) -> Option<&Map<String, Value>> {
371        match self {
372            Value::Object(map) => Some(map),
373            _ => None,
374        }
375    }
376
377    /// If the `Value` is an Object, returns the associated mutable Map.
378    /// Returns None otherwise.
379    ///
380    /// ```
381    /// # use serde_json::json;
382    /// #
383    /// let mut v = json!({ "a": { "nested": true } });
384    ///
385    /// v["a"].as_object_mut().unwrap().clear();
386    /// assert_eq!(v, json!({ "a": {} }));
387    /// ```
388    pub fn as_object_mut(&mut self) -> Option<&mut Map<String, Value>> {
389        match self {
390            Value::Object(map) => Some(map),
391            _ => None,
392        }
393    }
394
395    /// Returns true if the `Value` is an Array. Returns false otherwise.
396    ///
397    /// For any Value on which `is_array` returns true, `as_array` and
398    /// `as_array_mut` are guaranteed to return the vector representing the
399    /// array.
400    ///
401    /// ```
402    /// # use serde_json::json;
403    /// #
404    /// let obj = json!({ "a": ["an", "array"], "b": { "an": "object" } });
405    ///
406    /// assert!(obj["a"].is_array());
407    ///
408    /// // an object, not an array
409    /// assert!(!obj["b"].is_array());
410    /// ```
411    pub fn is_array(&self) -> bool {
412        self.as_array().is_some()
413    }
414
415    /// If the `Value` is an Array, returns the associated vector. Returns None
416    /// otherwise.
417    ///
418    /// ```
419    /// # use serde_json::json;
420    /// #
421    /// let v = json!({ "a": ["an", "array"], "b": { "an": "object" } });
422    ///
423    /// // The length of `["an", "array"]` is 2 elements.
424    /// assert_eq!(v["a"].as_array().unwrap().len(), 2);
425    ///
426    /// // The object `{"an": "object"}` is not an array.
427    /// assert_eq!(v["b"].as_array(), None);
428    /// ```
429    pub fn as_array(&self) -> Option<&Vec<Value>> {
430        match self {
431            Value::Array(array) => Some(array),
432            _ => None,
433        }
434    }
435
436    /// If the `Value` is an Array, returns the associated mutable vector.
437    /// Returns None otherwise.
438    ///
439    /// ```
440    /// # use serde_json::json;
441    /// #
442    /// let mut v = json!({ "a": ["an", "array"] });
443    ///
444    /// v["a"].as_array_mut().unwrap().clear();
445    /// assert_eq!(v, json!({ "a": [] }));
446    /// ```
447    pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> {
448        match self {
449            Value::Array(list) => Some(list),
450            _ => None,
451        }
452    }
453
454    /// Returns true if the `Value` is a String. Returns false otherwise.
455    ///
456    /// For any Value on which `is_string` returns true, `as_str` is guaranteed
457    /// to return the string slice.
458    ///
459    /// ```
460    /// # use serde_json::json;
461    /// #
462    /// let v = json!({ "a": "some string", "b": false });
463    ///
464    /// assert!(v["a"].is_string());
465    ///
466    /// // The boolean `false` is not a string.
467    /// assert!(!v["b"].is_string());
468    /// ```
469    pub fn is_string(&self) -> bool {
470        self.as_str().is_some()
471    }
472
473    /// If the `Value` is a String, returns the associated str. Returns None
474    /// otherwise.
475    ///
476    /// ```
477    /// # use serde_json::json;
478    /// #
479    /// let v = json!({ "a": "some string", "b": false });
480    ///
481    /// assert_eq!(v["a"].as_str(), Some("some string"));
482    ///
483    /// // The boolean `false` is not a string.
484    /// assert_eq!(v["b"].as_str(), None);
485    ///
486    /// // JSON values are printed in JSON representation, so strings are in quotes.
487    /// //
488    /// //    The value is: "some string"
489    /// println!("The value is: {}", v["a"]);
490    ///
491    /// // Rust strings are printed without quotes.
492    /// //
493    /// //    The value is: some string
494    /// println!("The value is: {}", v["a"].as_str().unwrap());
495    /// ```
496    pub fn as_str(&self) -> Option<&str> {
497        match self {
498            Value::String(s) => Some(s),
499            _ => None,
500        }
501    }
502
503    /// Returns true if the `Value` is a Number. Returns false otherwise.
504    ///
505    /// ```
506    /// # use serde_json::json;
507    /// #
508    /// let v = json!({ "a": 1, "b": "2" });
509    ///
510    /// assert!(v["a"].is_number());
511    ///
512    /// // The string `"2"` is a string, not a number.
513    /// assert!(!v["b"].is_number());
514    /// ```
515    pub fn is_number(&self) -> bool {
516        match *self {
517            Value::Number(_) => true,
518            _ => false,
519        }
520    }
521
522    /// If the `Value` is a Number, returns the associated [`Number`]. Returns
523    /// None otherwise.
524    ///
525    /// ```
526    /// # use serde_json::{json, Number};
527    /// #
528    /// let v = json!({ "a": 1, "b": 2.2, "c": -3, "d": "4" });
529    ///
530    /// assert_eq!(v["a"].as_number(), Some(&Number::from(1u64)));
531    /// assert_eq!(v["b"].as_number(), Some(&Number::from_f64(2.2).unwrap()));
532    /// assert_eq!(v["c"].as_number(), Some(&Number::from(-3i64)));
533    ///
534    /// // The string `"4"` is not a number.
535    /// assert_eq!(v["d"].as_number(), None);
536    /// ```
537    pub fn as_number(&self) -> Option<&Number> {
538        match self {
539            Value::Number(number) => Some(number),
540            _ => None,
541        }
542    }
543
544    /// Returns true if the `Value` is an integer between `i64::MIN` and
545    /// `i64::MAX`.
546    ///
547    /// For any Value on which `is_i64` returns true, `as_i64` is guaranteed to
548    /// return the integer value.
549    ///
550    /// ```
551    /// # use serde_json::json;
552    /// #
553    /// let big = i64::max_value() as u64 + 10;
554    /// let v = json!({ "a": 64, "b": big, "c": 256.0 });
555    ///
556    /// assert!(v["a"].is_i64());
557    ///
558    /// // Greater than i64::MAX.
559    /// assert!(!v["b"].is_i64());
560    ///
561    /// // Numbers with a decimal point are not considered integers.
562    /// assert!(!v["c"].is_i64());
563    /// ```
564    pub fn is_i64(&self) -> bool {
565        match self {
566            Value::Number(n) => n.is_i64(),
567            _ => false,
568        }
569    }
570
571    /// Returns true if the `Value` is an integer between zero and `u64::MAX`.
572    ///
573    /// For any Value on which `is_u64` returns true, `as_u64` is guaranteed to
574    /// return the integer value.
575    ///
576    /// ```
577    /// # use serde_json::json;
578    /// #
579    /// let v = json!({ "a": 64, "b": -64, "c": 256.0 });
580    ///
581    /// assert!(v["a"].is_u64());
582    ///
583    /// // Negative integer.
584    /// assert!(!v["b"].is_u64());
585    ///
586    /// // Numbers with a decimal point are not considered integers.
587    /// assert!(!v["c"].is_u64());
588    /// ```
589    pub fn is_u64(&self) -> bool {
590        match self {
591            Value::Number(n) => n.is_u64(),
592            _ => false,
593        }
594    }
595
596    /// Returns true if the `Value` is a number that can be represented by f64.
597    ///
598    /// For any Value on which `is_f64` returns true, `as_f64` is guaranteed to
599    /// return the floating point value.
600    ///
601    /// Currently this function returns true if and only if both `is_i64` and
602    /// `is_u64` return false but this is not a guarantee in the future.
603    ///
604    /// ```
605    /// # use serde_json::json;
606    /// #
607    /// let v = json!({ "a": 256.0, "b": 64, "c": -64 });
608    ///
609    /// assert!(v["a"].is_f64());
610    ///
611    /// // Integers.
612    /// assert!(!v["b"].is_f64());
613    /// assert!(!v["c"].is_f64());
614    /// ```
615    pub fn is_f64(&self) -> bool {
616        match self {
617            Value::Number(n) => n.is_f64(),
618            _ => false,
619        }
620    }
621
622    /// If the `Value` is an integer, represent it as i64 if possible. Returns
623    /// None otherwise.
624    ///
625    /// ```
626    /// # use serde_json::json;
627    /// #
628    /// let big = i64::max_value() as u64 + 10;
629    /// let v = json!({ "a": 64, "b": big, "c": 256.0 });
630    ///
631    /// assert_eq!(v["a"].as_i64(), Some(64));
632    /// assert_eq!(v["b"].as_i64(), None);
633    /// assert_eq!(v["c"].as_i64(), None);
634    /// ```
635    pub fn as_i64(&self) -> Option<i64> {
636        match self {
637            Value::Number(n) => n.as_i64(),
638            _ => None,
639        }
640    }
641
642    /// If the `Value` is an integer, represent it as u64 if possible. Returns
643    /// None otherwise.
644    ///
645    /// ```
646    /// # use serde_json::json;
647    /// #
648    /// let v = json!({ "a": 64, "b": -64, "c": 256.0 });
649    ///
650    /// assert_eq!(v["a"].as_u64(), Some(64));
651    /// assert_eq!(v["b"].as_u64(), None);
652    /// assert_eq!(v["c"].as_u64(), None);
653    /// ```
654    pub fn as_u64(&self) -> Option<u64> {
655        match self {
656            Value::Number(n) => n.as_u64(),
657            _ => None,
658        }
659    }
660
661    /// If the `Value` is a number, represent it as f64 if possible. Returns
662    /// None otherwise.
663    ///
664    /// ```
665    /// # use serde_json::json;
666    /// #
667    /// let v = json!({ "a": 256.0, "b": 64, "c": -64 });
668    ///
669    /// assert_eq!(v["a"].as_f64(), Some(256.0));
670    /// assert_eq!(v["b"].as_f64(), Some(64.0));
671    /// assert_eq!(v["c"].as_f64(), Some(-64.0));
672    /// ```
673    pub fn as_f64(&self) -> Option<f64> {
674        match self {
675            Value::Number(n) => n.as_f64(),
676            _ => None,
677        }
678    }
679
680    /// Returns true if the `Value` is a Boolean. Returns false otherwise.
681    ///
682    /// For any Value on which `is_boolean` returns true, `as_bool` is
683    /// guaranteed to return the boolean value.
684    ///
685    /// ```
686    /// # use serde_json::json;
687    /// #
688    /// let v = json!({ "a": false, "b": "false" });
689    ///
690    /// assert!(v["a"].is_boolean());
691    ///
692    /// // The string `"false"` is a string, not a boolean.
693    /// assert!(!v["b"].is_boolean());
694    /// ```
695    pub fn is_boolean(&self) -> bool {
696        self.as_bool().is_some()
697    }
698
699    /// If the `Value` is a Boolean, returns the associated bool. Returns None
700    /// otherwise.
701    ///
702    /// ```
703    /// # use serde_json::json;
704    /// #
705    /// let v = json!({ "a": false, "b": "false" });
706    ///
707    /// assert_eq!(v["a"].as_bool(), Some(false));
708    ///
709    /// // The string `"false"` is a string, not a boolean.
710    /// assert_eq!(v["b"].as_bool(), None);
711    /// ```
712    pub fn as_bool(&self) -> Option<bool> {
713        match *self {
714            Value::Bool(b) => Some(b),
715            _ => None,
716        }
717    }
718
719    /// Returns true if the `Value` is a Null. Returns false otherwise.
720    ///
721    /// For any Value on which `is_null` returns true, `as_null` is guaranteed
722    /// to return `Some(())`.
723    ///
724    /// ```
725    /// # use serde_json::json;
726    /// #
727    /// let v = json!({ "a": null, "b": false });
728    ///
729    /// assert!(v["a"].is_null());
730    ///
731    /// // The boolean `false` is not null.
732    /// assert!(!v["b"].is_null());
733    /// ```
734    pub fn is_null(&self) -> bool {
735        self.as_null().is_some()
736    }
737
738    /// If the `Value` is a Null, returns (). Returns None otherwise.
739    ///
740    /// ```
741    /// # use serde_json::json;
742    /// #
743    /// let v = json!({ "a": null, "b": false });
744    ///
745    /// assert_eq!(v["a"].as_null(), Some(()));
746    ///
747    /// // The boolean `false` is not null.
748    /// assert_eq!(v["b"].as_null(), None);
749    /// ```
750    pub fn as_null(&self) -> Option<()> {
751        match *self {
752            Value::Null => Some(()),
753            _ => None,
754        }
755    }
756
757    /// Looks up a value by a JSON Pointer.
758    ///
759    /// JSON Pointer defines a string syntax for identifying a specific value
760    /// within a JavaScript Object Notation (JSON) document.
761    ///
762    /// A Pointer is a Unicode string with the reference tokens separated by `/`.
763    /// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The
764    /// addressed value is returned and if there is no such value `None` is
765    /// returned.
766    ///
767    /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901).
768    ///
769    /// # Examples
770    ///
771    /// ```
772    /// # use serde_json::json;
773    /// #
774    /// let data = json!({
775    ///     "x": {
776    ///         "y": ["z", "zz"]
777    ///     }
778    /// });
779    ///
780    /// assert_eq!(data.pointer("/x/y/1").unwrap(), &json!("zz"));
781    /// assert_eq!(data.pointer("/a/b/c"), None);
782    /// ```
783    pub fn pointer(&self, pointer: &str) -> Option<&Value> {
784        if pointer.is_empty() {
785            return Some(self);
786        }
787        if !pointer.starts_with('/') {
788            return None;
789        }
790        pointer
791            .split('/')
792            .skip(1)
793            .map(|x| x.replace("~1", "/").replace("~0", "~"))
794            .try_fold(self, |target, token| match target {
795                Value::Object(map) => map.get(&token),
796                Value::Array(list) => parse_index(&token).and_then(|x| list.get(x)),
797                _ => None,
798            })
799    }
800
801    /// Looks up a value by a JSON Pointer and returns a mutable reference to
802    /// that value.
803    ///
804    /// JSON Pointer defines a string syntax for identifying a specific value
805    /// within a JavaScript Object Notation (JSON) document.
806    ///
807    /// A Pointer is a Unicode string with the reference tokens separated by `/`.
808    /// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The
809    /// addressed value is returned and if there is no such value `None` is
810    /// returned.
811    ///
812    /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901).
813    ///
814    /// # Example of Use
815    ///
816    /// ```
817    /// use serde_json::Value;
818    ///
819    /// fn main() {
820    ///     let s = r#"{"x": 1.0, "y": 2.0}"#;
821    ///     let mut value: Value = serde_json::from_str(s).unwrap();
822    ///
823    ///     // Check value using read-only pointer
824    ///     assert_eq!(value.pointer("/x"), Some(&1.0.into()));
825    ///     // Change value with direct assignment
826    ///     *value.pointer_mut("/x").unwrap() = 1.5.into();
827    ///     // Check that new value was written
828    ///     assert_eq!(value.pointer("/x"), Some(&1.5.into()));
829    ///     // Or change the value only if it exists
830    ///     value.pointer_mut("/x").map(|v| *v = 1.5.into());
831    ///
832    ///     // "Steal" ownership of a value. Can replace with any valid Value.
833    ///     let old_x = value.pointer_mut("/x").map(Value::take).unwrap();
834    ///     assert_eq!(old_x, 1.5);
835    ///     assert_eq!(value.pointer("/x").unwrap(), &Value::Null);
836    /// }
837    /// ```
838    pub fn pointer_mut(&mut self, pointer: &str) -> Option<&mut Value> {
839        if pointer.is_empty() {
840            return Some(self);
841        }
842        if !pointer.starts_with('/') {
843            return None;
844        }
845        pointer
846            .split('/')
847            .skip(1)
848            .map(|x| x.replace("~1", "/").replace("~0", "~"))
849            .try_fold(self, |target, token| match target {
850                Value::Object(map) => map.get_mut(&token),
851                Value::Array(list) => parse_index(&token).and_then(move |x| list.get_mut(x)),
852                _ => None,
853            })
854    }
855
856    /// Takes the value out of the `Value`, leaving a `Null` in its place.
857    ///
858    /// ```
859    /// # use serde_json::json;
860    /// #
861    /// let mut v = json!({ "x": "y" });
862    /// assert_eq!(v["x"].take(), json!("y"));
863    /// assert_eq!(v, json!({ "x": null }));
864    /// ```
865    pub fn take(&mut self) -> Value {
866        mem::replace(self, Value::Null)
867    }
868
869    /// Reorders the entries of all `Value::Object` nested within this JSON
870    /// value according to `str`'s usual ordering.
871    ///
872    /// If serde_json's "preserve_order" feature is not enabled, this method
873    /// does no work because all JSON maps are always kept in a sorted state.
874    ///
875    /// If serde_json's "preserve_order" feature is enabled, this method
876    /// destroys the original source order or insertion order of the JSON
877    /// objects in favor of an alphanumerical order that matches how a BTreeMap
878    /// with the same contents would be ordered.
879    pub fn sort_all_objects(&mut self) {
880        #[cfg(feature = "preserve_order")]
881        {
882            match self {
883                Value::Object(map) => {
884                    map.sort_keys();
885                    map.values_mut().for_each(Value::sort_all_objects);
886                }
887                Value::Array(list) => {
888                    list.iter_mut().for_each(Value::sort_all_objects);
889                }
890                _ => {}
891            }
892        }
893    }
894}
895
896/// The default value is `Value::Null`.
897///
898/// This is useful for handling omitted `Value` fields when deserializing.
899///
900/// # Examples
901///
902/// ```
903/// # use serde::Deserialize;
904/// use serde_json::Value;
905///
906/// #[derive(Deserialize)]
907/// struct Settings {
908///     level: i32,
909///     #[serde(default)]
910///     extras: Value,
911/// }
912///
913/// # fn try_main() -> Result<(), serde_json::Error> {
914/// let data = r#" { "level": 42 } "#;
915/// let s: Settings = serde_json::from_str(data)?;
916///
917/// assert_eq!(s.level, 42);
918/// assert_eq!(s.extras, Value::Null);
919/// #
920/// #     Ok(())
921/// # }
922/// #
923/// # try_main().unwrap()
924/// ```
925impl Default for Value {
926    fn default() -> Value {
927        Value::Null
928    }
929}
930
931impl Default for &Value {
932    fn default() -> Self {
933        const DEFAULT: Value = Value::Null;
934        &DEFAULT
935    }
936}
937
938mod de;
939mod from;
940mod index;
941mod partial_eq;
942mod ser;
943
944/// Convert a `T` into `serde_json::Value` which is an enum that can represent
945/// any valid JSON data.
946///
947/// # Example
948///
949/// ```
950/// use serde::Serialize;
951/// use serde_json::json;
952/// use std::error::Error;
953///
954/// #[derive(Serialize)]
955/// struct User {
956///     fingerprint: String,
957///     location: String,
958/// }
959///
960/// fn compare_json_values() -> Result<(), Box<dyn Error>> {
961///     let u = User {
962///         fingerprint: "0xF9BA143B95FF6D82".to_owned(),
963///         location: "Menlo Park, CA".to_owned(),
964///     };
965///
966///     // The type of `expected` is `serde_json::Value`
967///     let expected = json!({
968///         "fingerprint": "0xF9BA143B95FF6D82",
969///         "location": "Menlo Park, CA",
970///     });
971///
972///     let v = serde_json::to_value(u).unwrap();
973///     assert_eq!(v, expected);
974///
975///     Ok(())
976/// }
977/// #
978/// # compare_json_values().unwrap();
979/// ```
980///
981/// # Errors
982///
983/// This conversion can fail if `T`'s implementation of `Serialize` decides to
984/// fail, or if `T` contains a map with non-string keys.
985///
986/// ```
987/// use std::collections::BTreeMap;
988///
989/// fn main() {
990///     // The keys in this map are vectors, not strings.
991///     let mut map = BTreeMap::new();
992///     map.insert(vec![32, 64], "x86");
993///
994///     println!("{}", serde_json::to_value(map).unwrap_err());
995/// }
996/// ```
997// Taking by value is more friendly to iterator adapters, option and result
998// consumers, etc. See https://github.com/serde-rs/json/pull/149.
999pub fn to_value<T>(value: T) -> Result<Value, Error>
1000where
1001    T: Serialize,
1002{
1003    value.serialize(Serializer)
1004}
1005
1006/// Interpret a `serde_json::Value` as an instance of type `T`.
1007///
1008/// # Example
1009///
1010/// ```
1011/// use serde::Deserialize;
1012/// use serde_json::json;
1013///
1014/// #[derive(Deserialize, Debug)]
1015/// struct User {
1016///     fingerprint: String,
1017///     location: String,
1018/// }
1019///
1020/// fn main() {
1021///     // The type of `j` is `serde_json::Value`
1022///     let j = json!({
1023///         "fingerprint": "0xF9BA143B95FF6D82",
1024///         "location": "Menlo Park, CA"
1025///     });
1026///
1027///     let u: User = serde_json::from_value(j).unwrap();
1028///     println!("{:#?}", u);
1029/// }
1030/// ```
1031///
1032/// # Errors
1033///
1034/// This conversion can fail if the structure of the Value does not match the
1035/// structure expected by `T`, for example if `T` is a struct type but the Value
1036/// contains something other than a JSON map. It can also fail if the structure
1037/// is correct but `T`'s implementation of `Deserialize` decides that something
1038/// is wrong with the data, for example required struct fields are missing from
1039/// the JSON map or some number is too big to fit in the expected primitive
1040/// type.
1041pub fn from_value<T>(value: Value) -> Result<T, Error>
1042where
1043    T: DeserializeOwned,
1044{
1045    T::deserialize(value)
1046}