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