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