1 // Copyright 2017 Serde Developers
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.
9 //! The Value enum, a loosely typed way of representing any valid JSON value.
11 //! # Constructing JSON
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.
19 //! extern crate serde_json;
22 //! // The type of `john` is `serde_json::Value`
23 //! let john = json!({
24 //! "name": "John Doe",
32 //! println!("first phone number: {}", john["phones"][0]);
34 //! // Convert to a string of JSON and print it out
35 //! println!("{}", john.to_string());
39 //! The `Value::to_string()` function converts a `serde_json::Value` into a
40 //! `String` of JSON text.
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.
49 //! # extern crate serde_json;
51 //! # fn random_phone() -> u16 { 0 }
54 //! let full_name = "John Doe";
55 //! let age_last_year = 42;
57 //! // The type of `john` is `serde_json::Value`
58 //! let john = json!({
59 //! "name": full_name,
60 //! "age": age_last_year + 1,
62 //! format!("+44 {}", random_phone())
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
76 //! extern crate serde_json;
78 //! use serde_json::{Value, Error};
80 //! fn untyped_example() -> Result<(), Error> {
81 //! // Some JSON input data as a &str. Maybe this comes from the user.
83 //! "name": "John Doe",
91 //! // Parse the string of data into serde_json::Value.
92 //! let v: Value = serde_json::from_str(data)?;
94 //! // Access parts of the data by indexing with square brackets.
95 //! println!("Please call {} at the number {}", v["name"], v["phones"][0]);
101 //! # untyped_example().unwrap();
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
110 use std
::fmt
::{self, Debug}
;
115 use serde
::de
::DeserializeOwned
;
116 use serde
::ser
::Serialize
;
120 pub use number
::Number
;
122 #[cfg(feature = "raw_value")]
123 pub use raw
::RawValue
;
125 pub use self::index
::Index
;
127 use self::ser
::Serializer
;
129 /// Represents any valid JSON value.
131 /// See the `serde_json::value` module documentation for usage examples.
132 #[derive(Clone, PartialEq)]
134 /// Represents a JSON null value.
138 /// # extern crate serde_json;
141 /// let v = json!(null);
146 /// Represents a JSON boolean.
150 /// # extern crate serde_json;
153 /// let v = json!(true);
158 /// Represents a JSON number, whether integer or floating point.
162 /// # extern crate serde_json;
165 /// let v = json!(12.5);
170 /// Represents a JSON string.
174 /// # extern crate serde_json;
177 /// let v = json!("a string");
182 /// Represents a JSON array.
186 /// # extern crate serde_json;
189 /// let v = json!(["an", "array"]);
194 /// Represents a JSON object.
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.
204 /// # extern crate serde_json;
207 /// let v = json!({ "an": "object" });
210 Object(Map
<String
, Value
>),
213 impl Debug
for Value
{
214 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
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(),
226 struct WriterFormatter
<'a
, 'b
: 'a
> {
227 inner
: &'a
mut fmt
::Formatter
<'b
>,
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")
237 let s
= try
!(str::from_utf8(buf
).map_err(io_error
));
238 try
!(self.inner
.write_str(s
).map_err(io_error
));
242 fn flush(&mut self) -> io
::Result
<()> {
247 impl fmt
::Display
for Value
{
248 /// Display a JSON value as a string.
252 /// # extern crate serde_json;
255 /// let json = json!({ "city": "London", "street": "10 Downing Street" });
257 /// // Compact format:
259 /// // {"city":"London","street":"10 Downing Street"}
260 /// let compact = format!("{}", json);
261 /// assert_eq!(compact,
262 /// "{\"city\":\"London\",\"street\":\"10 Downing Street\"}");
264 /// // Pretty format:
267 /// // "city": "London",
268 /// // "street": "10 Downing Street"
270 /// let pretty = format!("{:#}", json);
271 /// assert_eq!(pretty,
272 /// "{\n \"city\": \"London\",\n \"street\": \"10 Downing Street\"\n}");
275 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
276 let alternate
= f
.alternate();
277 let mut wr
= WriterFormatter { inner: f }
;
280 super::ser
::to_writer_pretty(&mut wr
, self).map_err(|_
| fmt
::Error
)
283 super::ser
::to_writer(&mut wr
, self).map_err(|_
| fmt
::Error
)
288 fn parse_index(s
: &str) -> Option
<usize> {
289 if s
.starts_with('
+'
) || (s
.starts_with('
0'
) && s
.len() != 1) {
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
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.
307 /// # extern crate serde_json;
310 /// let object = json!({ "A": 65, "B": 66, "C": 67 });
311 /// assert_eq!(*object.get("A").unwrap(), json!(65));
313 /// let array = json!([ "A", "B", "C" ]);
314 /// assert_eq!(*array.get(2).unwrap(), json!("C"));
316 /// assert_eq!(array.get("A"), None);
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
326 /// # extern crate serde_json;
329 /// let object = json!({
330 /// "A": ["a", "á", "à"],
331 /// "B": ["b", "b́"],
332 /// "C": ["c", "ć", "ć̣", "ḉ"],
334 /// assert_eq!(object["B"][0], json!("b"));
336 /// assert_eq!(object["D"], json!(null));
337 /// assert_eq!(object[0]["x"]["y"]["z"], json!(null));
340 pub fn get
<I
: Index
>(&self, index
: I
) -> Option
<&Value
> {
341 index
.index_into(self)
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.
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.
355 /// # extern crate serde_json;
358 /// let mut object = json!({ "A": 65, "B": 66, "C": 67 });
359 /// *object.get_mut("A").unwrap() = json!(69);
361 /// let mut array = json!([ "A", "B", "C" ]);
362 /// *array.get_mut(2).unwrap() = json!("D");
365 pub fn get_mut
<I
: Index
>(&mut self, index
: I
) -> Option
<&mut Value
> {
366 index
.index_into_mut(self)
369 /// Returns true if the `Value` is an Object. Returns false otherwise.
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
377 /// # extern crate serde_json;
380 /// let obj = json!({ "a": { "nested": true }, "b": ["an", "array"] });
382 /// assert!(obj.is_object());
383 /// assert!(obj["a"].is_object());
385 /// // array, not an object
386 /// assert!(!obj["b"].is_object());
389 pub fn is_object(&self) -> bool
{
390 self.as_object().is_some()
393 /// If the `Value` is an Object, returns the associated Map. Returns None
398 /// # extern crate serde_json;
401 /// let v = json!({ "a": { "nested": true }, "b": ["an", "array"] });
403 /// // The length of `{"nested": true}` is 1 entry.
404 /// assert_eq!(v["a"].as_object().unwrap().len(), 1);
406 /// // The array `["an", "array"]` is not an object.
407 /// assert_eq!(v["b"].as_object(), None);
410 pub fn as_object(&self) -> Option
<&Map
<String
, Value
>> {
412 Value
::Object(ref map
) => Some(map
),
417 /// If the `Value` is an Object, returns the associated mutable Map.
418 /// Returns None otherwise.
422 /// # extern crate serde_json;
425 /// let mut v = json!({ "a": { "nested": true } });
427 /// v["a"].as_object_mut().unwrap().clear();
428 /// assert_eq!(v, json!({ "a": {} }));
432 pub fn as_object_mut(&mut self) -> Option
<&mut Map
<String
, Value
>> {
434 Value
::Object(ref mut map
) => Some(map
),
439 /// Returns true if the `Value` is an Array. Returns false otherwise.
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
447 /// # extern crate serde_json;
450 /// let obj = json!({ "a": ["an", "array"], "b": { "an": "object" } });
452 /// assert!(obj["a"].is_array());
454 /// // an object, not an array
455 /// assert!(!obj["b"].is_array());
458 pub fn is_array(&self) -> bool
{
459 self.as_array().is_some()
462 /// If the `Value` is an Array, returns the associated vector. Returns None
467 /// # extern crate serde_json;
470 /// let v = json!({ "a": ["an", "array"], "b": { "an": "object" } });
472 /// // The length of `["an", "array"]` is 2 elements.
473 /// assert_eq!(v["a"].as_array().unwrap().len(), 2);
475 /// // The object `{"an": "object"}` is not an array.
476 /// assert_eq!(v["b"].as_array(), None);
479 pub fn as_array(&self) -> Option
<&Vec
<Value
>> {
481 Value
::Array(ref array
) => Some(&*array
),
486 /// If the `Value` is an Array, returns the associated mutable vector.
487 /// Returns None otherwise.
491 /// # extern crate serde_json;
494 /// let mut v = json!({ "a": ["an", "array"] });
496 /// v["a"].as_array_mut().unwrap().clear();
497 /// assert_eq!(v, json!({ "a": [] }));
500 pub fn as_array_mut(&mut self) -> Option
<&mut Vec
<Value
>> {
502 Value
::Array(ref mut list
) => Some(list
),
507 /// Returns true if the `Value` is a String. Returns false otherwise.
509 /// For any Value on which `is_string` returns true, `as_str` is guaranteed
510 /// to return the string slice.
514 /// # extern crate serde_json;
517 /// let v = json!({ "a": "some string", "b": false });
519 /// assert!(v["a"].is_string());
521 /// // The boolean `false` is not a string.
522 /// assert!(!v["b"].is_string());
525 pub fn is_string(&self) -> bool
{
526 self.as_str().is_some()
529 /// If the `Value` is a String, returns the associated str. Returns None
534 /// # extern crate serde_json;
537 /// let v = json!({ "a": "some string", "b": false });
539 /// assert_eq!(v["a"].as_str(), Some("some string"));
541 /// // The boolean `false` is not a string.
542 /// assert_eq!(v["b"].as_str(), None);
544 /// // JSON values are printed in JSON representation, so strings are in quotes.
546 /// // The value is: "some string"
547 /// println!("The value is: {}", v["a"]);
549 /// // Rust strings are printed without quotes.
551 /// // The value is: some string
552 /// println!("The value is: {}", v["a"].as_str().unwrap());
555 pub fn as_str(&self) -> Option
<&str> {
557 Value
::String(ref s
) => Some(s
),
562 /// Returns true if the `Value` is a Number. Returns false otherwise.
566 /// # extern crate serde_json;
569 /// let v = json!({ "a": 1, "b": "2" });
571 /// assert!(v["a"].is_number());
573 /// // The string `"2"` is a string, not a number.
574 /// assert!(!v["b"].is_number());
577 pub fn is_number(&self) -> bool
{
579 Value
::Number(_
) => true,
584 /// Returns true if the `Value` is an integer between `i64::MIN` and
587 /// For any Value on which `is_i64` returns true, `as_i64` is guaranteed to
588 /// return the integer value.
592 /// # extern crate serde_json;
595 /// let big = i64::max_value() as u64 + 10;
596 /// let v = json!({ "a": 64, "b": big, "c": 256.0 });
598 /// assert!(v["a"].is_i64());
600 /// // Greater than i64::MAX.
601 /// assert!(!v["b"].is_i64());
603 /// // Numbers with a decimal point are not considered integers.
604 /// assert!(!v["c"].is_i64());
607 pub fn is_i64(&self) -> bool
{
609 Value
::Number(ref n
) => n
.is_i64(),
614 /// Returns true if the `Value` is an integer between zero and `u64::MAX`.
616 /// For any Value on which `is_u64` returns true, `as_u64` is guaranteed to
617 /// return the integer value.
621 /// # extern crate serde_json;
624 /// let v = json!({ "a": 64, "b": -64, "c": 256.0 });
626 /// assert!(v["a"].is_u64());
628 /// // Negative integer.
629 /// assert!(!v["b"].is_u64());
631 /// // Numbers with a decimal point are not considered integers.
632 /// assert!(!v["c"].is_u64());
635 pub fn is_u64(&self) -> bool
{
637 Value
::Number(ref n
) => n
.is_u64(),
642 /// Returns true if the `Value` is a number that can be represented by f64.
644 /// For any Value on which `is_f64` returns true, `as_f64` is guaranteed to
645 /// return the floating point value.
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.
652 /// # extern crate serde_json;
655 /// let v = json!({ "a": 256.0, "b": 64, "c": -64 });
657 /// assert!(v["a"].is_f64());
660 /// assert!(!v["b"].is_f64());
661 /// assert!(!v["c"].is_f64());
664 pub fn is_f64(&self) -> bool
{
666 Value
::Number(ref n
) => n
.is_f64(),
671 /// If the `Value` is an integer, represent it as i64 if possible. Returns
676 /// # extern crate serde_json;
679 /// let big = i64::max_value() as u64 + 10;
680 /// let v = json!({ "a": 64, "b": big, "c": 256.0 });
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);
687 pub fn as_i64(&self) -> Option
<i64> {
689 Value
::Number(ref n
) => n
.as_i64(),
694 /// If the `Value` is an integer, represent it as u64 if possible. Returns
699 /// # extern crate serde_json;
702 /// let v = json!({ "a": 64, "b": -64, "c": 256.0 });
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);
709 pub fn as_u64(&self) -> Option
<u64> {
711 Value
::Number(ref n
) => n
.as_u64(),
716 /// If the `Value` is a number, represent it as f64 if possible. Returns
721 /// # extern crate serde_json;
724 /// let v = json!({ "a": 256.0, "b": 64, "c": -64 });
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));
731 pub fn as_f64(&self) -> Option
<f64> {
733 Value
::Number(ref n
) => n
.as_f64(),
738 /// Returns true if the `Value` is a Boolean. Returns false otherwise.
740 /// For any Value on which `is_boolean` returns true, `as_bool` is
741 /// guaranteed to return the boolean value.
745 /// # extern crate serde_json;
748 /// let v = json!({ "a": false, "b": "false" });
750 /// assert!(v["a"].is_boolean());
752 /// // The string `"false"` is a string, not a boolean.
753 /// assert!(!v["b"].is_boolean());
756 pub fn is_boolean(&self) -> bool
{
757 self.as_bool().is_some()
760 /// If the `Value` is a Boolean, returns the associated bool. Returns None
765 /// # extern crate serde_json;
768 /// let v = json!({ "a": false, "b": "false" });
770 /// assert_eq!(v["a"].as_bool(), Some(false));
772 /// // The string `"false"` is a string, not a boolean.
773 /// assert_eq!(v["b"].as_bool(), None);
776 pub fn as_bool(&self) -> Option
<bool
> {
778 Value
::Bool(b
) => Some(b
),
783 /// Returns true if the `Value` is a Null. Returns false otherwise.
785 /// For any Value on which `is_null` returns true, `as_null` is guaranteed
786 /// to return `Some(())`.
790 /// # extern crate serde_json;
793 /// let v = json!({ "a": null, "b": false });
795 /// assert!(v["a"].is_null());
797 /// // The boolean `false` is not null.
798 /// assert!(!v["b"].is_null());
801 pub fn is_null(&self) -> bool
{
802 self.as_null().is_some()
805 /// If the `Value` is a Null, returns (). Returns None otherwise.
809 /// # extern crate serde_json;
812 /// let v = json!({ "a": null, "b": false });
814 /// assert_eq!(v["a"].as_null(), Some(()));
816 /// // The boolean `false` is not null.
817 /// assert_eq!(v["b"].as_null(), None);
820 pub fn as_null(&self) -> Option
<()> {
822 Value
::Null
=> Some(()),
827 /// Looks up a value by a JSON Pointer.
829 /// JSON Pointer defines a string syntax for identifying a specific value
830 /// within a JavaScript Object Notation (JSON) document.
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
837 /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901).
843 /// # extern crate serde_json;
846 /// let data = json!({
852 /// assert_eq!(data.pointer("/x/y/1").unwrap(), &json!("zz"));
853 /// assert_eq!(data.pointer("/a/b/c"), None);
856 pub fn pointer
<'a
>(&'a
self, pointer
: &str) -> Option
<&'a Value
> {
860 if !pointer
.starts_with('
/'
) {
866 .map(|x
| x
.replace("~1", "/").replace("~0", "~"));
867 let mut target
= self;
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
)),
875 if let Some(t
) = target_opt
{
884 /// Looks up a value by a JSON Pointer and returns a mutable reference to
887 /// JSON Pointer defines a string syntax for identifying a specific value
888 /// within a JavaScript Object Notation (JSON) document.
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
895 /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901).
900 /// extern crate serde_json;
902 /// use serde_json::Value;
905 /// let s = r#"{"x": 1.0, "y": 2.0}"#;
906 /// let mut value: Value = serde_json::from_str(s).unwrap();
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()));
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);
921 pub fn pointer_mut
<'a
>(&'a
mut self, pointer
: &str) -> Option
<&'a
mut Value
> {
925 if !pointer
.starts_with('
/'
) {
931 .map(|x
| x
.replace("~1", "/").replace("~0", "~"));
932 let mut target
= self;
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
))
945 if let Some(t
) = target_opt
{
954 /// Takes the value out of the `Value`, leaving a `Null` in its place.
958 /// # extern crate serde_json;
961 /// let mut v = json!({ "x": "y" });
962 /// assert_eq!(v["x"].take(), json!("y"));
963 /// assert_eq!(v, json!({ "x": null }));
966 pub fn take(&mut self) -> Value
{
967 mem
::replace(self, Value
::Null
)
971 /// The default value is `Value::Null`.
973 /// This is useful for handling omitted `Value` fields when deserializing.
979 /// # extern crate serde_derive;
981 /// # extern crate serde_json;
983 /// use serde_json::Value;
985 /// #[derive(Deserialize)]
986 /// struct Settings {
988 /// #[serde(default)]
992 /// # fn try_main() -> Result<(), serde_json::Error> {
993 /// let data = r#" { "level": 42 } "#;
994 /// let s: Settings = serde_json::from_str(data)?;
996 /// assert_eq!(s.level, 42);
997 /// assert_eq!(s.extras, Value::Null);
1003 /// # try_main().unwrap()
1006 impl Default
for Value
{
1007 fn default() -> Value
{
1018 /// Convert a `T` into `serde_json::Value` which is an enum that can represent
1019 /// any valid JSON data.
1022 /// extern crate serde;
1025 /// extern crate serde_derive;
1028 /// extern crate serde_json;
1030 /// use std::error::Error;
1032 /// #[derive(Serialize)]
1034 /// fingerprint: String,
1035 /// location: String,
1038 /// fn compare_json_values() -> Result<(), Box<Error>> {
1040 /// fingerprint: "0xF9BA143B95FF6D82".to_owned(),
1041 /// location: "Menlo Park, CA".to_owned(),
1044 /// // The type of `expected` is `serde_json::Value`
1045 /// let expected = json!({
1046 /// "fingerprint": "0xF9BA143B95FF6D82",
1047 /// "location": "Menlo Park, CA",
1050 /// let v = serde_json::to_value(u).unwrap();
1051 /// assert_eq!(v, expected);
1057 /// # compare_json_values().unwrap();
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.
1067 /// extern crate serde_json;
1069 /// use std::collections::BTreeMap;
1072 /// // The keys in this map are vectors, not strings.
1073 /// let mut map = BTreeMap::new();
1074 /// map.insert(vec![32, 64], "x86");
1076 /// println!("{}", serde_json::to_value(map).unwrap_err());
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
>
1085 value
.serialize(Serializer
)
1088 /// Interpret a `serde_json::Value` as an instance of type `T`.
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
1100 /// extern crate serde_json;
1103 /// extern crate serde_derive;
1105 /// extern crate serde;
1107 /// #[derive(Deserialize, Debug)]
1109 /// fingerprint: String,
1110 /// location: String,
1114 /// // The type of `j` is `serde_json::Value`
1116 /// "fingerprint": "0xF9BA143B95FF6D82",
1117 /// "location": "Menlo Park, CA"
1120 /// let u: User = serde_json::from_value(j).unwrap();
1121 /// println!("{:#?}", u);
1124 pub fn from_value
<T
>(value
: Value
) -> Result
<T
, Error
>
1126 T
: DeserializeOwned
,
1128 T
::deserialize(value
)