1 //! The Value enum, a loosely typed way of representing any valid JSON value.
3 //! # Constructing JSON
5 //! Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value`
6 //! objects with very natural JSON syntax.
9 //! use serde_json::json;
12 //! // The type of `john` is `serde_json::Value`
13 //! let john = json!({
14 //! "name": "John Doe",
22 //! println!("first phone number: {}", john["phones"][0]);
24 //! // Convert to a string of JSON and print it out
25 //! println!("{}", john.to_string());
29 //! The `Value::to_string()` function converts a `serde_json::Value` into a
30 //! `String` of JSON text.
32 //! One neat thing about the `json!` macro is that variables and expressions can
33 //! be interpolated directly into the JSON value as you are building it. Serde
34 //! will check at compile time that the value you are interpolating is able to
35 //! be represented as JSON.
38 //! # use serde_json::json;
40 //! # fn random_phone() -> u16 { 0 }
42 //! let full_name = "John Doe";
43 //! let age_last_year = 42;
45 //! // The type of `john` is `serde_json::Value`
46 //! let john = json!({
47 //! "name": full_name,
48 //! "age": age_last_year + 1,
50 //! format!("+44 {}", random_phone())
55 //! A string of JSON data can be parsed into a `serde_json::Value` by the
56 //! [`serde_json::from_str`][from_str] function. There is also
57 //! [`from_slice`][from_slice] for parsing from a byte slice `&[u8]` and
58 //! [`from_reader`][from_reader] for parsing from any `io::Read` like a File or
62 //! use serde_json::{json, Value, Error};
64 //! fn untyped_example() -> Result<(), Error> {
65 //! // Some JSON input data as a &str. Maybe this comes from the user.
68 //! "name": "John Doe",
76 //! // Parse the string of data into serde_json::Value.
77 //! let v: Value = serde_json::from_str(data)?;
79 //! // Access parts of the data by indexing with square brackets.
80 //! println!("Please call {} at the number {}", v["name"], v["phones"][0]);
85 //! # untyped_example().unwrap();
88 //! [macro]: https://docs.serde.rs/serde_json/macro.json.html
89 //! [from_str]: https://docs.serde.rs/serde_json/de/fn.from_str.html
90 //! [from_slice]: https://docs.serde.rs/serde_json/de/fn.from_slice.html
91 //! [from_reader]: https://docs.serde.rs/serde_json/de/fn.from_reader.html
93 use crate::error
::Error
;
96 use serde
::de
::DeserializeOwned
;
97 use serde
::ser
::Serialize
;
99 pub use self::index
::Index
;
100 pub use self::ser
::Serializer
;
101 pub use crate::map
::Map
;
102 pub use crate::number
::Number
;
104 #[cfg(feature = "raw_value")]
105 pub use crate::raw
::{to_raw_value, RawValue}
;
107 /// Represents any valid JSON value.
109 /// See the `serde_json::value` module documentation for usage examples.
110 #[derive(Clone, Eq, PartialEq)]
112 /// Represents a JSON null value.
115 /// # use serde_json::json;
117 /// let v = json!(null);
121 /// Represents a JSON boolean.
124 /// # use serde_json::json;
126 /// let v = json!(true);
130 /// Represents a JSON number, whether integer or floating point.
133 /// # use serde_json::json;
135 /// let v = json!(12.5);
139 /// Represents a JSON string.
142 /// # use serde_json::json;
144 /// let v = json!("a string");
148 /// Represents a JSON array.
151 /// # use serde_json::json;
153 /// let v = json!(["an", "array"]);
157 /// Represents a JSON object.
159 /// By default the map is backed by a BTreeMap. Enable the `preserve_order`
160 /// feature of serde_json to use IndexMap instead, which preserves
161 /// entries in the order they are inserted into the map. In particular, this
162 /// allows JSON data to be deserialized into a Value and serialized to a
163 /// string while retaining the order of map keys in the input.
166 /// # use serde_json::json;
168 /// let v = json!({ "an": "object" });
170 Object(Map
<String
, Value
>),
173 impl Debug
for Value
{
174 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
176 Value
::Null
=> formatter
.debug_tuple("Null").finish(),
177 Value
::Bool(v
) => formatter
.debug_tuple("Bool").field(&v
).finish(),
178 Value
::Number(ref v
) => Debug
::fmt(v
, formatter
),
179 Value
::String(ref v
) => formatter
.debug_tuple("String").field(v
).finish(),
180 Value
::Array(ref v
) => {
181 formatter
.write_str("Array(")?
;
182 Debug
::fmt(v
, formatter
)?
;
183 formatter
.write_str(")")
185 Value
::Object(ref v
) => {
186 formatter
.write_str("Object(")?
;
187 Debug
::fmt(v
, formatter
)?
;
188 formatter
.write_str(")")
194 struct WriterFormatter
<'a
, 'b
: 'a
> {
195 inner
: &'a
mut fmt
::Formatter
<'b
>,
198 impl<'a
, 'b
> io
::Write
for WriterFormatter
<'a
, 'b
> {
199 fn write(&mut self, buf
: &[u8]) -> io
::Result
<usize> {
200 fn io_error
<E
>(_
: E
) -> io
::Error
{
201 // Error value does not matter because fmt::Display impl below just
202 // maps it to fmt::Error
203 io
::Error
::new(io
::ErrorKind
::Other
, "fmt error")
205 let s
= tri
!(str::from_utf8(buf
).map_err(io_error
));
206 tri
!(self.inner
.write_str(s
).map_err(io_error
));
210 fn flush(&mut self) -> io
::Result
<()> {
215 impl fmt
::Display
for Value
{
216 /// Display a JSON value as a string.
219 /// # use serde_json::json;
221 /// let json = json!({ "city": "London", "street": "10 Downing Street" });
223 /// // Compact format:
225 /// // {"city":"London","street":"10 Downing Street"}
226 /// let compact = format!("{}", json);
227 /// assert_eq!(compact,
228 /// "{\"city\":\"London\",\"street\":\"10 Downing Street\"}");
230 /// // Pretty format:
233 /// // "city": "London",
234 /// // "street": "10 Downing Street"
236 /// let pretty = format!("{:#}", json);
237 /// assert_eq!(pretty,
238 /// "{\n \"city\": \"London\",\n \"street\": \"10 Downing Street\"\n}");
240 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
241 let alternate
= f
.alternate();
242 let mut wr
= WriterFormatter { inner: f }
;
245 super::ser
::to_writer_pretty(&mut wr
, self).map_err(|_
| fmt
::Error
)
248 super::ser
::to_writer(&mut wr
, self).map_err(|_
| fmt
::Error
)
253 fn parse_index(s
: &str) -> Option
<usize> {
254 if s
.starts_with('
+'
) || (s
.starts_with('
0'
) && s
.len() != 1) {
261 /// Index into a JSON array or map. A string index can be used to access a
262 /// value in a map, and a usize index can be used to access an element of an
265 /// Returns `None` if the type of `self` does not match the type of the
266 /// index, for example if the index is a string and `self` is an array or a
267 /// number. Also returns `None` if the given key does not exist in the map
268 /// or the given index is not within the bounds of the array.
271 /// # use serde_json::json;
273 /// let object = json!({ "A": 65, "B": 66, "C": 67 });
274 /// assert_eq!(*object.get("A").unwrap(), json!(65));
276 /// let array = json!([ "A", "B", "C" ]);
277 /// assert_eq!(*array.get(2).unwrap(), json!("C"));
279 /// assert_eq!(array.get("A"), None);
282 /// Square brackets can also be used to index into a value in a more concise
283 /// way. This returns `Value::Null` in cases where `get` would have returned
287 /// # use serde_json::json;
289 /// let object = json!({
290 /// "A": ["a", "á", "à"],
291 /// "B": ["b", "b́"],
292 /// "C": ["c", "ć", "ć̣", "ḉ"],
294 /// assert_eq!(object["B"][0], json!("b"));
296 /// assert_eq!(object["D"], json!(null));
297 /// assert_eq!(object[0]["x"]["y"]["z"], json!(null));
299 pub fn get
<I
: Index
>(&self, index
: I
) -> Option
<&Value
> {
300 index
.index_into(self)
303 /// Mutably index into a JSON array or map. A string index can be used to
304 /// access a value in a map, and a usize index can be used to access an
305 /// element of an array.
307 /// Returns `None` if the type of `self` does not match the type of the
308 /// index, for example if the index is a string and `self` is an array or a
309 /// number. Also returns `None` if the given key does not exist in the map
310 /// or the given index is not within the bounds of the array.
313 /// # use serde_json::json;
315 /// let mut object = json!({ "A": 65, "B": 66, "C": 67 });
316 /// *object.get_mut("A").unwrap() = json!(69);
318 /// let mut array = json!([ "A", "B", "C" ]);
319 /// *array.get_mut(2).unwrap() = json!("D");
321 pub fn get_mut
<I
: Index
>(&mut self, index
: I
) -> Option
<&mut Value
> {
322 index
.index_into_mut(self)
325 /// Returns true if the `Value` is an Object. Returns false otherwise.
327 /// For any Value on which `is_object` returns true, `as_object` and
328 /// `as_object_mut` are guaranteed to return the map representation of the
332 /// # use serde_json::json;
334 /// let obj = json!({ "a": { "nested": true }, "b": ["an", "array"] });
336 /// assert!(obj.is_object());
337 /// assert!(obj["a"].is_object());
339 /// // array, not an object
340 /// assert!(!obj["b"].is_object());
342 pub fn is_object(&self) -> bool
{
343 self.as_object().is_some()
346 /// If the `Value` is an Object, returns the associated Map. Returns None
350 /// # use serde_json::json;
352 /// let v = json!({ "a": { "nested": true }, "b": ["an", "array"] });
354 /// // The length of `{"nested": true}` is 1 entry.
355 /// assert_eq!(v["a"].as_object().unwrap().len(), 1);
357 /// // The array `["an", "array"]` is not an object.
358 /// assert_eq!(v["b"].as_object(), None);
360 pub fn as_object(&self) -> Option
<&Map
<String
, Value
>> {
362 Value
::Object(ref map
) => Some(map
),
367 /// If the `Value` is an Object, returns the associated mutable Map.
368 /// Returns None otherwise.
371 /// # use serde_json::json;
373 /// let mut v = json!({ "a": { "nested": true } });
375 /// v["a"].as_object_mut().unwrap().clear();
376 /// assert_eq!(v, json!({ "a": {} }));
378 pub fn as_object_mut(&mut self) -> Option
<&mut Map
<String
, Value
>> {
380 Value
::Object(ref mut map
) => Some(map
),
385 /// Returns true if the `Value` is an Array. Returns false otherwise.
387 /// For any Value on which `is_array` returns true, `as_array` and
388 /// `as_array_mut` are guaranteed to return the vector representing the
392 /// # use serde_json::json;
394 /// let obj = json!({ "a": ["an", "array"], "b": { "an": "object" } });
396 /// assert!(obj["a"].is_array());
398 /// // an object, not an array
399 /// assert!(!obj["b"].is_array());
401 pub fn is_array(&self) -> bool
{
402 self.as_array().is_some()
405 /// If the `Value` is an Array, returns the associated vector. Returns None
409 /// # use serde_json::json;
411 /// let v = json!({ "a": ["an", "array"], "b": { "an": "object" } });
413 /// // The length of `["an", "array"]` is 2 elements.
414 /// assert_eq!(v["a"].as_array().unwrap().len(), 2);
416 /// // The object `{"an": "object"}` is not an array.
417 /// assert_eq!(v["b"].as_array(), None);
419 pub fn as_array(&self) -> Option
<&Vec
<Value
>> {
421 Value
::Array(ref array
) => Some(&*array
),
426 /// If the `Value` is an Array, returns the associated mutable vector.
427 /// Returns None otherwise.
430 /// # use serde_json::json;
432 /// let mut v = json!({ "a": ["an", "array"] });
434 /// v["a"].as_array_mut().unwrap().clear();
435 /// assert_eq!(v, json!({ "a": [] }));
437 pub fn as_array_mut(&mut self) -> Option
<&mut Vec
<Value
>> {
439 Value
::Array(ref mut list
) => Some(list
),
444 /// Returns true if the `Value` is a String. Returns false otherwise.
446 /// For any Value on which `is_string` returns true, `as_str` is guaranteed
447 /// to return the string slice.
450 /// # use serde_json::json;
452 /// let v = json!({ "a": "some string", "b": false });
454 /// assert!(v["a"].is_string());
456 /// // The boolean `false` is not a string.
457 /// assert!(!v["b"].is_string());
459 pub fn is_string(&self) -> bool
{
460 self.as_str().is_some()
463 /// If the `Value` is a String, returns the associated str. Returns None
467 /// # use serde_json::json;
469 /// let v = json!({ "a": "some string", "b": false });
471 /// assert_eq!(v["a"].as_str(), Some("some string"));
473 /// // The boolean `false` is not a string.
474 /// assert_eq!(v["b"].as_str(), None);
476 /// // JSON values are printed in JSON representation, so strings are in quotes.
478 /// // The value is: "some string"
479 /// println!("The value is: {}", v["a"]);
481 /// // Rust strings are printed without quotes.
483 /// // The value is: some string
484 /// println!("The value is: {}", v["a"].as_str().unwrap());
486 pub fn as_str(&self) -> Option
<&str> {
488 Value
::String(ref s
) => Some(s
),
493 /// Returns true if the `Value` is a Number. Returns false otherwise.
496 /// # use serde_json::json;
498 /// let v = json!({ "a": 1, "b": "2" });
500 /// assert!(v["a"].is_number());
502 /// // The string `"2"` is a string, not a number.
503 /// assert!(!v["b"].is_number());
505 pub fn is_number(&self) -> bool
{
507 Value
::Number(_
) => true,
512 /// Returns true if the `Value` is an integer between `i64::MIN` and
515 /// For any Value on which `is_i64` returns true, `as_i64` is guaranteed to
516 /// return the integer value.
519 /// # use serde_json::json;
521 /// let big = i64::max_value() as u64 + 10;
522 /// let v = json!({ "a": 64, "b": big, "c": 256.0 });
524 /// assert!(v["a"].is_i64());
526 /// // Greater than i64::MAX.
527 /// assert!(!v["b"].is_i64());
529 /// // Numbers with a decimal point are not considered integers.
530 /// assert!(!v["c"].is_i64());
532 pub fn is_i64(&self) -> bool
{
534 Value
::Number(ref n
) => n
.is_i64(),
539 /// Returns true if the `Value` is an integer between zero and `u64::MAX`.
541 /// For any Value on which `is_u64` returns true, `as_u64` is guaranteed to
542 /// return the integer value.
545 /// # use serde_json::json;
547 /// let v = json!({ "a": 64, "b": -64, "c": 256.0 });
549 /// assert!(v["a"].is_u64());
551 /// // Negative integer.
552 /// assert!(!v["b"].is_u64());
554 /// // Numbers with a decimal point are not considered integers.
555 /// assert!(!v["c"].is_u64());
557 pub fn is_u64(&self) -> bool
{
559 Value
::Number(ref n
) => n
.is_u64(),
564 /// Returns true if the `Value` is a number that can be represented by f64.
566 /// For any Value on which `is_f64` returns true, `as_f64` is guaranteed to
567 /// return the floating point value.
569 /// Currently this function returns true if and only if both `is_i64` and
570 /// `is_u64` return false but this is not a guarantee in the future.
573 /// # use serde_json::json;
575 /// let v = json!({ "a": 256.0, "b": 64, "c": -64 });
577 /// assert!(v["a"].is_f64());
580 /// assert!(!v["b"].is_f64());
581 /// assert!(!v["c"].is_f64());
583 pub fn is_f64(&self) -> bool
{
585 Value
::Number(ref n
) => n
.is_f64(),
590 /// If the `Value` is an integer, represent it as i64 if possible. Returns
594 /// # use serde_json::json;
596 /// let big = i64::max_value() as u64 + 10;
597 /// let v = json!({ "a": 64, "b": big, "c": 256.0 });
599 /// assert_eq!(v["a"].as_i64(), Some(64));
600 /// assert_eq!(v["b"].as_i64(), None);
601 /// assert_eq!(v["c"].as_i64(), None);
603 pub fn as_i64(&self) -> Option
<i64> {
605 Value
::Number(ref n
) => n
.as_i64(),
610 /// If the `Value` is an integer, represent it as u64 if possible. Returns
614 /// # use serde_json::json;
616 /// let v = json!({ "a": 64, "b": -64, "c": 256.0 });
618 /// assert_eq!(v["a"].as_u64(), Some(64));
619 /// assert_eq!(v["b"].as_u64(), None);
620 /// assert_eq!(v["c"].as_u64(), None);
622 pub fn as_u64(&self) -> Option
<u64> {
624 Value
::Number(ref n
) => n
.as_u64(),
629 /// If the `Value` is a number, represent it as f64 if possible. Returns
633 /// # use serde_json::json;
635 /// let v = json!({ "a": 256.0, "b": 64, "c": -64 });
637 /// assert_eq!(v["a"].as_f64(), Some(256.0));
638 /// assert_eq!(v["b"].as_f64(), Some(64.0));
639 /// assert_eq!(v["c"].as_f64(), Some(-64.0));
641 pub fn as_f64(&self) -> Option
<f64> {
643 Value
::Number(ref n
) => n
.as_f64(),
648 /// Returns true if the `Value` is a Boolean. Returns false otherwise.
650 /// For any Value on which `is_boolean` returns true, `as_bool` is
651 /// guaranteed to return the boolean value.
654 /// # use serde_json::json;
656 /// let v = json!({ "a": false, "b": "false" });
658 /// assert!(v["a"].is_boolean());
660 /// // The string `"false"` is a string, not a boolean.
661 /// assert!(!v["b"].is_boolean());
663 pub fn is_boolean(&self) -> bool
{
664 self.as_bool().is_some()
667 /// If the `Value` is a Boolean, returns the associated bool. Returns None
671 /// # use serde_json::json;
673 /// let v = json!({ "a": false, "b": "false" });
675 /// assert_eq!(v["a"].as_bool(), Some(false));
677 /// // The string `"false"` is a string, not a boolean.
678 /// assert_eq!(v["b"].as_bool(), None);
680 pub fn as_bool(&self) -> Option
<bool
> {
682 Value
::Bool(b
) => Some(b
),
687 /// Returns true if the `Value` is a Null. Returns false otherwise.
689 /// For any Value on which `is_null` returns true, `as_null` is guaranteed
690 /// to return `Some(())`.
693 /// # use serde_json::json;
695 /// let v = json!({ "a": null, "b": false });
697 /// assert!(v["a"].is_null());
699 /// // The boolean `false` is not null.
700 /// assert!(!v["b"].is_null());
702 pub fn is_null(&self) -> bool
{
703 self.as_null().is_some()
706 /// If the `Value` is a Null, returns (). Returns None otherwise.
709 /// # use serde_json::json;
711 /// let v = json!({ "a": null, "b": false });
713 /// assert_eq!(v["a"].as_null(), Some(()));
715 /// // The boolean `false` is not null.
716 /// assert_eq!(v["b"].as_null(), None);
718 pub fn as_null(&self) -> Option
<()> {
720 Value
::Null
=> Some(()),
725 /// Looks up a value by a JSON Pointer.
727 /// JSON Pointer defines a string syntax for identifying a specific value
728 /// within a JavaScript Object Notation (JSON) document.
730 /// A Pointer is a Unicode string with the reference tokens separated by `/`.
731 /// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The
732 /// addressed value is returned and if there is no such value `None` is
735 /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901).
740 /// # use serde_json::json;
742 /// let data = json!({
748 /// assert_eq!(data.pointer("/x/y/1").unwrap(), &json!("zz"));
749 /// assert_eq!(data.pointer("/a/b/c"), None);
751 pub fn pointer(&self, pointer
: &str) -> Option
<&Value
> {
752 if pointer
.is_empty() {
755 if !pointer
.starts_with('
/'
) {
761 .map(|x
| x
.replace("~1", "/").replace("~0", "~"));
762 let mut target
= self;
764 for token
in tokens
{
765 let target_opt
= match *target
{
766 Value
::Object(ref map
) => map
.get(&token
),
767 Value
::Array(ref list
) => parse_index(&token
).and_then(|x
| list
.get(x
)),
770 if let Some(t
) = target_opt
{
779 /// Looks up a value by a JSON Pointer and returns a mutable reference to
782 /// JSON Pointer defines a string syntax for identifying a specific value
783 /// within a JavaScript Object Notation (JSON) document.
785 /// A Pointer is a Unicode string with the reference tokens separated by `/`.
786 /// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The
787 /// addressed value is returned and if there is no such value `None` is
790 /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901).
795 /// use serde_json::Value;
798 /// let s = r#"{"x": 1.0, "y": 2.0}"#;
799 /// let mut value: Value = serde_json::from_str(s).unwrap();
801 /// // Check value using read-only pointer
802 /// assert_eq!(value.pointer("/x"), Some(&1.0.into()));
803 /// // Change value with direct assignment
804 /// *value.pointer_mut("/x").unwrap() = 1.5.into();
805 /// // Check that new value was written
806 /// assert_eq!(value.pointer("/x"), Some(&1.5.into()));
807 /// // Or change the value only if it exists
808 /// value.pointer_mut("/x").map(|v| *v = 1.5.into());
810 /// // "Steal" ownership of a value. Can replace with any valid Value.
811 /// let old_x = value.pointer_mut("/x").map(Value::take).unwrap();
812 /// assert_eq!(old_x, 1.5);
813 /// assert_eq!(value.pointer("/x").unwrap(), &Value::Null);
816 pub fn pointer_mut(&mut self, pointer
: &str) -> Option
<&mut Value
> {
817 if pointer
.is_empty() {
820 if !pointer
.starts_with('
/'
) {
826 .map(|x
| x
.replace("~1", "/").replace("~0", "~"));
827 let mut target
= self;
829 for token
in tokens
{
830 // borrow checker gets confused about `target` being mutably borrowed too many times because of the loop
831 // this once-per-loop binding makes the scope clearer and circumvents the error
832 let target_once
= target
;
833 let target_opt
= match *target_once
{
834 Value
::Object(ref mut map
) => map
.get_mut(&token
),
835 Value
::Array(ref mut list
) => {
836 parse_index(&token
).and_then(move |x
| list
.get_mut(x
))
840 if let Some(t
) = target_opt
{
849 /// Takes the value out of the `Value`, leaving a `Null` in its place.
852 /// # use serde_json::json;
854 /// let mut v = json!({ "x": "y" });
855 /// assert_eq!(v["x"].take(), json!("y"));
856 /// assert_eq!(v, json!({ "x": null }));
858 pub fn take(&mut self) -> Value
{
859 mem
::replace(self, Value
::Null
)
863 /// The default value is `Value::Null`.
865 /// This is useful for handling omitted `Value` fields when deserializing.
870 /// # use serde::Deserialize;
871 /// use serde_json::Value;
873 /// #[derive(Deserialize)]
874 /// struct Settings {
876 /// #[serde(default)]
880 /// # fn try_main() -> Result<(), serde_json::Error> {
881 /// let data = r#" { "level": 42 } "#;
882 /// let s: Settings = serde_json::from_str(data)?;
884 /// assert_eq!(s.level, 42);
885 /// assert_eq!(s.extras, Value::Null);
890 /// # try_main().unwrap()
892 impl Default
for Value
{
893 fn default() -> Value
{
904 /// Convert a `T` into `serde_json::Value` which is an enum that can represent
905 /// any valid JSON data.
910 /// use serde::Serialize;
911 /// use serde_json::json;
913 /// use std::error::Error;
915 /// #[derive(Serialize)]
917 /// fingerprint: String,
918 /// location: String,
921 /// fn compare_json_values() -> Result<(), Box<Error>> {
923 /// fingerprint: "0xF9BA143B95FF6D82".to_owned(),
924 /// location: "Menlo Park, CA".to_owned(),
927 /// // The type of `expected` is `serde_json::Value`
928 /// let expected = json!({
929 /// "fingerprint": "0xF9BA143B95FF6D82",
930 /// "location": "Menlo Park, CA",
933 /// let v = serde_json::to_value(u).unwrap();
934 /// assert_eq!(v, expected);
939 /// # compare_json_values().unwrap();
944 /// This conversion can fail if `T`'s implementation of `Serialize` decides to
945 /// fail, or if `T` contains a map with non-string keys.
948 /// use std::collections::BTreeMap;
951 /// // The keys in this map are vectors, not strings.
952 /// let mut map = BTreeMap::new();
953 /// map.insert(vec![32, 64], "x86");
955 /// println!("{}", serde_json::to_value(map).unwrap_err());
958 // Taking by value is more friendly to iterator adapters, option and result
959 // consumers, etc. See https://github.com/serde-rs/json/pull/149.
960 pub fn to_value
<T
>(value
: T
) -> Result
<Value
, Error
>
964 value
.serialize(Serializer
)
967 /// Interpret a `serde_json::Value` as an instance of type `T`.
972 /// use serde::Deserialize;
973 /// use serde_json::json;
975 /// #[derive(Deserialize, Debug)]
977 /// fingerprint: String,
978 /// location: String,
982 /// // The type of `j` is `serde_json::Value`
984 /// "fingerprint": "0xF9BA143B95FF6D82",
985 /// "location": "Menlo Park, CA"
988 /// let u: User = serde_json::from_value(j).unwrap();
989 /// println!("{:#?}", u);
995 /// This conversion can fail if the structure of the Value does not match the
996 /// structure expected by `T`, for example if `T` is a struct type but the Value
997 /// contains something other than a JSON map. It can also fail if the structure
998 /// is correct but `T`'s implementation of `Deserialize` decides that something
999 /// is wrong with the data, for example required struct fields are missing from
1000 /// the JSON map or some number is too big to fit in the expected primitive
1002 pub fn from_value
<T
>(value
: Value
) -> Result
<T
, Error
>
1004 T
: DeserializeOwned
,
1006 T
::deserialize(value
)