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(data:"Null"),
181 Value::Bool(boolean: &bool) => write!(formatter, "Bool({})", boolean),
182 Value::Number(number: &Number) => Debug::fmt(self:number, f:formatter),
183 Value::String(string: &String) => write!(formatter, "String({:?})", string),
184 Value::Array(vec: &Vec) => {
185 formatter.write_str(data:"Array ")?;
186 Debug::fmt(self:vec, f:formatter)
187 }
188 Value::Object(map: &Map) => {
189 formatter.write_str(data:"Object ")?;
190 Debug::fmt(self:map, f: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 /// Returns true if the `Value` is an integer between `i64::MIN` and
518 /// `i64::MAX`.
519 ///
520 /// For any Value on which `is_i64` returns true, `as_i64` is guaranteed to
521 /// return the integer value.
522 ///
523 /// ```
524 /// # use serde_json::json;
525 /// #
526 /// let big = i64::max_value() as u64 + 10;
527 /// let v = json!({ "a": 64, "b": big, "c": 256.0 });
528 ///
529 /// assert!(v["a"].is_i64());
530 ///
531 /// // Greater than i64::MAX.
532 /// assert!(!v["b"].is_i64());
533 ///
534 /// // Numbers with a decimal point are not considered integers.
535 /// assert!(!v["c"].is_i64());
536 /// ```
537 pub fn is_i64(&self) -> bool {
538 match self {
539 Value::Number(n) => n.is_i64(),
540 _ => false,
541 }
542 }
543
544 /// Returns true if the `Value` is an integer between zero and `u64::MAX`.
545 ///
546 /// For any Value on which `is_u64` returns true, `as_u64` is guaranteed to
547 /// return the integer value.
548 ///
549 /// ```
550 /// # use serde_json::json;
551 /// #
552 /// let v = json!({ "a": 64, "b": -64, "c": 256.0 });
553 ///
554 /// assert!(v["a"].is_u64());
555 ///
556 /// // Negative integer.
557 /// assert!(!v["b"].is_u64());
558 ///
559 /// // Numbers with a decimal point are not considered integers.
560 /// assert!(!v["c"].is_u64());
561 /// ```
562 pub fn is_u64(&self) -> bool {
563 match self {
564 Value::Number(n) => n.is_u64(),
565 _ => false,
566 }
567 }
568
569 /// Returns true if the `Value` is a number that can be represented by f64.
570 ///
571 /// For any Value on which `is_f64` returns true, `as_f64` is guaranteed to
572 /// return the floating point value.
573 ///
574 /// Currently this function returns true if and only if both `is_i64` and
575 /// `is_u64` return false but this is not a guarantee in the future.
576 ///
577 /// ```
578 /// # use serde_json::json;
579 /// #
580 /// let v = json!({ "a": 256.0, "b": 64, "c": -64 });
581 ///
582 /// assert!(v["a"].is_f64());
583 ///
584 /// // Integers.
585 /// assert!(!v["b"].is_f64());
586 /// assert!(!v["c"].is_f64());
587 /// ```
588 pub fn is_f64(&self) -> bool {
589 match self {
590 Value::Number(n) => n.is_f64(),
591 _ => false,
592 }
593 }
594
595 /// If the `Value` is an integer, represent it as i64 if possible. Returns
596 /// None otherwise.
597 ///
598 /// ```
599 /// # use serde_json::json;
600 /// #
601 /// let big = i64::max_value() as u64 + 10;
602 /// let v = json!({ "a": 64, "b": big, "c": 256.0 });
603 ///
604 /// assert_eq!(v["a"].as_i64(), Some(64));
605 /// assert_eq!(v["b"].as_i64(), None);
606 /// assert_eq!(v["c"].as_i64(), None);
607 /// ```
608 pub fn as_i64(&self) -> Option<i64> {
609 match self {
610 Value::Number(n) => n.as_i64(),
611 _ => None,
612 }
613 }
614
615 /// If the `Value` is an integer, represent it as u64 if possible. Returns
616 /// None otherwise.
617 ///
618 /// ```
619 /// # use serde_json::json;
620 /// #
621 /// let v = json!({ "a": 64, "b": -64, "c": 256.0 });
622 ///
623 /// assert_eq!(v["a"].as_u64(), Some(64));
624 /// assert_eq!(v["b"].as_u64(), None);
625 /// assert_eq!(v["c"].as_u64(), None);
626 /// ```
627 pub fn as_u64(&self) -> Option<u64> {
628 match self {
629 Value::Number(n) => n.as_u64(),
630 _ => None,
631 }
632 }
633
634 /// If the `Value` is a number, represent it as f64 if possible. Returns
635 /// None otherwise.
636 ///
637 /// ```
638 /// # use serde_json::json;
639 /// #
640 /// let v = json!({ "a": 256.0, "b": 64, "c": -64 });
641 ///
642 /// assert_eq!(v["a"].as_f64(), Some(256.0));
643 /// assert_eq!(v["b"].as_f64(), Some(64.0));
644 /// assert_eq!(v["c"].as_f64(), Some(-64.0));
645 /// ```
646 pub fn as_f64(&self) -> Option<f64> {
647 match self {
648 Value::Number(n) => n.as_f64(),
649 _ => None,
650 }
651 }
652
653 /// Returns true if the `Value` is a Boolean. Returns false otherwise.
654 ///
655 /// For any Value on which `is_boolean` returns true, `as_bool` is
656 /// guaranteed to return the boolean value.
657 ///
658 /// ```
659 /// # use serde_json::json;
660 /// #
661 /// let v = json!({ "a": false, "b": "false" });
662 ///
663 /// assert!(v["a"].is_boolean());
664 ///
665 /// // The string `"false"` is a string, not a boolean.
666 /// assert!(!v["b"].is_boolean());
667 /// ```
668 pub fn is_boolean(&self) -> bool {
669 self.as_bool().is_some()
670 }
671
672 /// If the `Value` is a Boolean, returns the associated bool. Returns None
673 /// otherwise.
674 ///
675 /// ```
676 /// # use serde_json::json;
677 /// #
678 /// let v = json!({ "a": false, "b": "false" });
679 ///
680 /// assert_eq!(v["a"].as_bool(), Some(false));
681 ///
682 /// // The string `"false"` is a string, not a boolean.
683 /// assert_eq!(v["b"].as_bool(), None);
684 /// ```
685 pub fn as_bool(&self) -> Option<bool> {
686 match *self {
687 Value::Bool(b) => Some(b),
688 _ => None,
689 }
690 }
691
692 /// Returns true if the `Value` is a Null. Returns false otherwise.
693 ///
694 /// For any Value on which `is_null` returns true, `as_null` is guaranteed
695 /// to return `Some(())`.
696 ///
697 /// ```
698 /// # use serde_json::json;
699 /// #
700 /// let v = json!({ "a": null, "b": false });
701 ///
702 /// assert!(v["a"].is_null());
703 ///
704 /// // The boolean `false` is not null.
705 /// assert!(!v["b"].is_null());
706 /// ```
707 pub fn is_null(&self) -> bool {
708 self.as_null().is_some()
709 }
710
711 /// If the `Value` is a Null, returns (). Returns None otherwise.
712 ///
713 /// ```
714 /// # use serde_json::json;
715 /// #
716 /// let v = json!({ "a": null, "b": false });
717 ///
718 /// assert_eq!(v["a"].as_null(), Some(()));
719 ///
720 /// // The boolean `false` is not null.
721 /// assert_eq!(v["b"].as_null(), None);
722 /// ```
723 pub fn as_null(&self) -> Option<()> {
724 match *self {
725 Value::Null => Some(()),
726 _ => None,
727 }
728 }
729
730 /// Looks up a value by a JSON Pointer.
731 ///
732 /// JSON Pointer defines a string syntax for identifying a specific value
733 /// within a JavaScript Object Notation (JSON) document.
734 ///
735 /// A Pointer is a Unicode string with the reference tokens separated by `/`.
736 /// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The
737 /// addressed value is returned and if there is no such value `None` is
738 /// returned.
739 ///
740 /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901).
741 ///
742 /// # Examples
743 ///
744 /// ```
745 /// # use serde_json::json;
746 /// #
747 /// let data = json!({
748 /// "x": {
749 /// "y": ["z", "zz"]
750 /// }
751 /// });
752 ///
753 /// assert_eq!(data.pointer("/x/y/1").unwrap(), &json!("zz"));
754 /// assert_eq!(data.pointer("/a/b/c"), None);
755 /// ```
756 pub fn pointer(&self, pointer: &str) -> Option<&Value> {
757 if pointer.is_empty() {
758 return Some(self);
759 }
760 if !pointer.starts_with('/') {
761 return None;
762 }
763 pointer
764 .split('/')
765 .skip(1)
766 .map(|x| x.replace("~1", "/").replace("~0", "~"))
767 .try_fold(self, |target, token| match target {
768 Value::Object(map) => map.get(&token),
769 Value::Array(list) => parse_index(&token).and_then(|x| list.get(x)),
770 _ => None,
771 })
772 }
773
774 /// Looks up a value by a JSON Pointer and returns a mutable reference to
775 /// that value.
776 ///
777 /// JSON Pointer defines a string syntax for identifying a specific value
778 /// within a JavaScript Object Notation (JSON) document.
779 ///
780 /// A Pointer is a Unicode string with the reference tokens separated by `/`.
781 /// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The
782 /// addressed value is returned and if there is no such value `None` is
783 /// returned.
784 ///
785 /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901).
786 ///
787 /// # Example of Use
788 ///
789 /// ```
790 /// use serde_json::Value;
791 ///
792 /// fn main() {
793 /// let s = r#"{"x": 1.0, "y": 2.0}"#;
794 /// let mut value: Value = serde_json::from_str(s).unwrap();
795 ///
796 /// // Check value using read-only pointer
797 /// assert_eq!(value.pointer("/x"), Some(&1.0.into()));
798 /// // Change value with direct assignment
799 /// *value.pointer_mut("/x").unwrap() = 1.5.into();
800 /// // Check that new value was written
801 /// assert_eq!(value.pointer("/x"), Some(&1.5.into()));
802 /// // Or change the value only if it exists
803 /// value.pointer_mut("/x").map(|v| *v = 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 /// ```
811 pub fn pointer_mut(&mut self, pointer: &str) -> Option<&mut Value> {
812 if pointer.is_empty() {
813 return Some(self);
814 }
815 if !pointer.starts_with('/') {
816 return None;
817 }
818 pointer
819 .split('/')
820 .skip(1)
821 .map(|x| x.replace("~1", "/").replace("~0", "~"))
822 .try_fold(self, |target, token| match target {
823 Value::Object(map) => map.get_mut(&token),
824 Value::Array(list) => parse_index(&token).and_then(move |x| list.get_mut(x)),
825 _ => None,
826 })
827 }
828
829 /// Takes the value out of the `Value`, leaving a `Null` in its place.
830 ///
831 /// ```
832 /// # use serde_json::json;
833 /// #
834 /// let mut v = json!({ "x": "y" });
835 /// assert_eq!(v["x"].take(), json!("y"));
836 /// assert_eq!(v, json!({ "x": null }));
837 /// ```
838 pub fn take(&mut self) -> Value {
839 mem::replace(self, Value::Null)
840 }
841}
842
843/// The default value is `Value::Null`.
844///
845/// This is useful for handling omitted `Value` fields when deserializing.
846///
847/// # Examples
848///
849/// ```
850/// # use serde::Deserialize;
851/// use serde_json::Value;
852///
853/// #[derive(Deserialize)]
854/// struct Settings {
855/// level: i32,
856/// #[serde(default)]
857/// extras: Value,
858/// }
859///
860/// # fn try_main() -> Result<(), serde_json::Error> {
861/// let data = r#" { "level": 42 } "#;
862/// let s: Settings = serde_json::from_str(data)?;
863///
864/// assert_eq!(s.level, 42);
865/// assert_eq!(s.extras, Value::Null);
866/// #
867/// # Ok(())
868/// # }
869/// #
870/// # try_main().unwrap()
871/// ```
872impl Default for Value {
873 fn default() -> Value {
874 Value::Null
875 }
876}
877
878mod de;
879mod from;
880mod index;
881mod partial_eq;
882mod ser;
883
884/// Convert a `T` into `serde_json::Value` which is an enum that can represent
885/// any valid JSON data.
886///
887/// # Example
888///
889/// ```
890/// use serde::Serialize;
891/// use serde_json::json;
892///
893/// use std::error::Error;
894///
895/// #[derive(Serialize)]
896/// struct User {
897/// fingerprint: String,
898/// location: String,
899/// }
900///
901/// fn compare_json_values() -> Result<(), Box<Error>> {
902/// let u = User {
903/// fingerprint: "0xF9BA143B95FF6D82".to_owned(),
904/// location: "Menlo Park, CA".to_owned(),
905/// };
906///
907/// // The type of `expected` is `serde_json::Value`
908/// let expected = json!({
909/// "fingerprint": "0xF9BA143B95FF6D82",
910/// "location": "Menlo Park, CA",
911/// });
912///
913/// let v = serde_json::to_value(u).unwrap();
914/// assert_eq!(v, expected);
915///
916/// Ok(())
917/// }
918/// #
919/// # compare_json_values().unwrap();
920/// ```
921///
922/// # Errors
923///
924/// This conversion can fail if `T`'s implementation of `Serialize` decides to
925/// fail, or if `T` contains a map with non-string keys.
926///
927/// ```
928/// use std::collections::BTreeMap;
929///
930/// fn main() {
931/// // The keys in this map are vectors, not strings.
932/// let mut map = BTreeMap::new();
933/// map.insert(vec![32, 64], "x86");
934///
935/// println!("{}", serde_json::to_value(map).unwrap_err());
936/// }
937/// ```
938// Taking by value is more friendly to iterator adapters, option and result
939// consumers, etc. See https://github.com/serde-rs/json/pull/149.
940pub fn to_value<T>(value: T) -> Result<Value, Error>
941where
942 T: Serialize,
943{
944 value.serialize(Serializer)
945}
946
947/// Interpret a `serde_json::Value` as an instance of type `T`.
948///
949/// # Example
950///
951/// ```
952/// use serde::Deserialize;
953/// use serde_json::json;
954///
955/// #[derive(Deserialize, Debug)]
956/// struct User {
957/// fingerprint: String,
958/// location: String,
959/// }
960///
961/// fn main() {
962/// // The type of `j` is `serde_json::Value`
963/// let j = json!({
964/// "fingerprint": "0xF9BA143B95FF6D82",
965/// "location": "Menlo Park, CA"
966/// });
967///
968/// let u: User = serde_json::from_value(j).unwrap();
969/// println!("{:#?}", u);
970/// }
971/// ```
972///
973/// # Errors
974///
975/// This conversion can fail if the structure of the Value does not match the
976/// structure expected by `T`, for example if `T` is a struct type but the Value
977/// contains something other than a JSON map. It can also fail if the structure
978/// is correct but `T`'s implementation of `Deserialize` decides that something
979/// is wrong with the data, for example required struct fields are missing from
980/// the JSON map or some number is too big to fit in the expected primitive
981/// type.
982pub fn from_value<T>(value: Value) -> Result<T, Error>
983where
984 T: DeserializeOwned,
985{
986 T::deserialize(deserializer:value)
987}
988