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