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