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