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