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