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