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