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