]> git.proxmox.com Git - rustc.git/blob - src/vendor/serde_json/src/value.rs
New upstream version 1.18.0+dfsg1
[rustc.git] / src / vendor / serde_json / src / value.rs
1 //! The Value enum, a loosely typed way of representing any valid JSON value.
2 //!
3 //! # Constructing JSON
4 //!
5 //! Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value`
6 //! objects with very natural JSON syntax. In order to use this macro,
7 //! `serde_json` needs to be imported with the `#[macro_use]` attribute.
8 //!
9 //! ```rust
10 //! #[macro_use]
11 //! extern crate serde_json;
12 //!
13 //! fn main() {
14 //! // The type of `john` is `serde_json::Value`
15 //! let john = json!({
16 //! "name": "John Doe",
17 //! "age": 43,
18 //! "phones": [
19 //! "+44 1234567",
20 //! "+44 2345678"
21 //! ]
22 //! });
23 //!
24 //! println!("first phone number: {}", john["phones"][0]);
25 //!
26 //! // Convert to a string of JSON and print it out
27 //! println!("{}", john.to_string());
28 //! }
29 //! ```
30 //!
31 //! The `Value::to_string()` function converts a `serde_json::Value` into a
32 //! `String` of JSON text.
33 //!
34 //! One neat thing about the `json!` macro is that variables and expressions can
35 //! be interpolated directly into the JSON value as you are building it. Serde
36 //! will check at compile time that the value you are interpolating is able to
37 //! be represented as JSON.
38 //!
39 //! ```rust
40 //! # #[macro_use] extern crate serde_json;
41 //! # fn random_phone() -> u16 { 0 }
42 //! # fn main() {
43 //! let full_name = "John Doe";
44 //! let age_last_year = 42;
45 //!
46 //! // The type of `john` is `serde_json::Value`
47 //! let john = json!({
48 //! "name": full_name,
49 //! "age": age_last_year + 1,
50 //! "phones": [
51 //! format!("+44 {}", random_phone())
52 //! ]
53 //! });
54 //! # let _ = john;
55 //! # }
56 //! ```
57 //!
58 //! A string of JSON data can be parsed into a `serde_json::Value` by the
59 //! [`serde_json::from_str`][from_str] function. There is also
60 //! [`from_slice`][from_slice] for parsing from a byte slice &[u8],
61 //! [`from_iter`][from_iter] for parsing from an iterator of bytes, and
62 //! [`from_reader`][from_reader] for parsing from any `io::Read` like a File or
63 //! a TCP stream.
64 //!
65 //! ```rust
66 //! # extern crate serde_json;
67 //! # use serde_json::Error;
68 //! # pub fn example() -> Result<(), Error> {
69 //! use serde_json::Value;
70 //!
71 //! let data = r#" { "name": "John Doe", "age": 43, ... } "#;
72 //! let v: Value = serde_json::from_str(data)?;
73 //! println!("Please call {} at the number {}", v["name"], v["phones"][0]);
74 //! # Ok(()) }
75 //! # fn main() {}
76 //! ```
77 //!
78 //! [macro]: https://docs.serde.rs/serde_json/macro.json.html
79 //! [from_str]: https://docs.serde.rs/serde_json/de/fn.from_str.html
80 //! [from_slice]: https://docs.serde.rs/serde_json/de/fn.from_slice.html
81 //! [from_iter]: https://docs.serde.rs/serde_json/de/fn.from_iter.html
82 //! [from_reader]: https://docs.serde.rs/serde_json/de/fn.from_reader.html
83
84 use std::fmt;
85 use std::i64;
86 use std::io;
87 use std::ops;
88 use std::slice;
89 use std::str;
90 use std::vec;
91 use std::borrow::Cow;
92
93 use serde::de::{self, Unexpected};
94 use serde::ser;
95 use serde::de::value::ValueDeserializer;
96
97 use error::{Error, ErrorCode};
98
99 pub use map::Map;
100 pub use number::Number;
101
102 /// Represents any valid JSON value.
103 #[derive(Debug, Clone, PartialEq)]
104 pub enum Value {
105 /// Represents a JSON null value.
106 Null,
107
108 /// Represents a JSON boolean.
109 Bool(bool),
110
111 /// Represents a JSON number, whether integer or floating point.
112 Number(Number),
113
114 /// Represents a JSON string.
115 String(String),
116
117 /// Represents a JSON array.
118 Array(Vec<Value>),
119
120 /// Represents a JSON object.
121 Object(Map<String, Value>),
122 }
123
124 fn parse_index(s: &str) -> Option<usize> {
125 if s.starts_with('+') || (s.starts_with('0') && s.len() != 1) {
126 return None;
127 }
128 s.parse().ok()
129 }
130
131 impl Value {
132 /// Index into a JSON array or map. A string index can be used to access a
133 /// value in a map, and a usize index can be used to access an element of an
134 /// array.
135 ///
136 /// Returns `None` if the type of `self` does not match the type of the
137 /// index, for example if the index is a string and `self` is an array or a
138 /// number. Also returns `None` if the given key does not exist in the map
139 /// or the given index is not within the bounds of the array.
140 ///
141 /// ```rust
142 /// # #[macro_use] extern crate serde_json;
143 /// # fn main() {
144 /// let object = json!({ "A": 65, "B": 66, "C": 67 });
145 /// assert_eq!(*object.get("A").unwrap(), json!(65));
146 ///
147 /// let array = json!([ "A", "B", "C" ]);
148 /// assert_eq!(*array.get(2).unwrap(), json!("C"));
149 ///
150 /// assert_eq!(array.get("A"), None);
151 /// # }
152 /// ```
153 ///
154 /// Square brackets can also be used to index into a value in a more concise
155 /// way. This returns `Value::Null` in cases where `get` would have returned
156 /// `None`.
157 ///
158 /// ```rust
159 /// # #[macro_use] extern crate serde_json;
160 /// # fn main() {
161 /// let object = json!({
162 /// "A": ["a", "á", "à"],
163 /// "B": ["b", "b́"],
164 /// "C": ["c", "ć", "ć̣", "ḉ"],
165 /// });
166 /// assert_eq!(object["B"][0], json!("b"));
167 ///
168 /// assert_eq!(object["D"], json!(null));
169 /// assert_eq!(object[0]["x"]["y"]["z"], json!(null));
170 /// # }
171 /// ```
172 pub fn get<I: Index>(&self, index: I) -> Option<&Value> {
173 index.index_into(self)
174 }
175
176 /// Mutably index into a JSON array or map. A string index can be used to
177 /// access a value in a map, and a usize index can be used to access an
178 /// element of an array.
179 ///
180 /// Returns `None` if the type of `self` does not match the type of the
181 /// index, for example if the index is a string and `self` is an array or a
182 /// number. Also returns `None` if the given key does not exist in the map
183 /// or the given index is not within the bounds of the array.
184 ///
185 /// ```rust
186 /// # #[macro_use] extern crate serde_json;
187 /// # fn main() {
188 /// let mut object = json!({ "A": 65, "B": 66, "C": 67 });
189 /// *object.get_mut("A").unwrap() = json!(69);
190 ///
191 /// let mut array = json!([ "A", "B", "C" ]);
192 /// *array.get_mut(2).unwrap() = json!("D");
193 /// # }
194 /// ```
195 pub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut Value> {
196 index.index_into_mut(self)
197 }
198
199 /// Returns true if the `Value` is an Object. Returns false otherwise.
200 pub fn is_object(&self) -> bool {
201 self.as_object().is_some()
202 }
203
204 /// If the `Value` is an Object, returns the associated Map.
205 /// Returns None otherwise.
206 pub fn as_object(&self) -> Option<&Map<String, Value>> {
207 match *self {
208 Value::Object(ref map) => Some(map),
209 _ => None,
210 }
211 }
212
213 /// If the `Value` is an Object, returns the associated mutable Map.
214 /// Returns None otherwise.
215 pub fn as_object_mut(&mut self) -> Option<&mut Map<String, Value>> {
216 match *self {
217 Value::Object(ref mut map) => Some(map),
218 _ => None,
219 }
220 }
221
222 /// Returns true if the `Value` is an Array. Returns false otherwise.
223 pub fn is_array(&self) -> bool {
224 self.as_array().is_some()
225 }
226
227 /// If the `Value` is an Array, returns the associated vector.
228 /// Returns None otherwise.
229 pub fn as_array(&self) -> Option<&Vec<Value>> {
230 match *self {
231 Value::Array(ref array) => Some(&*array),
232 _ => None,
233 }
234 }
235
236 /// If the `Value` is an Array, returns the associated mutable vector.
237 /// Returns None otherwise.
238 pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> {
239 match *self {
240 Value::Array(ref mut list) => Some(list),
241 _ => None,
242 }
243 }
244
245 /// Returns true if the `Value` is a String. Returns false otherwise.
246 pub fn is_string(&self) -> bool {
247 self.as_str().is_some()
248 }
249
250 /// If the `Value` is a String, returns the associated str.
251 /// Returns None otherwise.
252 pub fn as_str(&self) -> Option<&str> {
253 match *self {
254 Value::String(ref s) => Some(s),
255 _ => None,
256 }
257 }
258
259 /// Returns true if the `Value` is a Number. Returns false otherwise.
260 pub fn is_number(&self) -> bool {
261 match *self {
262 Value::Number(_) => true,
263 _ => false,
264 }
265 }
266
267 /// Returns true if the `Value` is a number that can be represented by i64.
268 pub fn is_i64(&self) -> bool {
269 match *self {
270 Value::Number(ref n) => n.is_i64(),
271 _ => false,
272 }
273 }
274
275 /// Returns true if the `Value` is a number that can be represented by u64.
276 pub fn is_u64(&self) -> bool {
277 match *self {
278 Value::Number(ref n) => n.is_u64(),
279 _ => false,
280 }
281 }
282
283 /// Returns true if the `Value` is a number that can be represented by f64.
284 pub fn is_f64(&self) -> bool {
285 match *self {
286 Value::Number(ref n) => n.is_f64(),
287 _ => false,
288 }
289 }
290
291 /// If the `Value` is a number, represent it as i64 if possible.
292 /// Returns None otherwise.
293 pub fn as_i64(&self) -> Option<i64> {
294 match *self {
295 Value::Number(ref n) => n.as_i64(),
296 _ => None,
297 }
298 }
299
300 /// If the `Value` is a number, represent it as u64 if possible.
301 /// Returns None otherwise.
302 pub fn as_u64(&self) -> Option<u64> {
303 match *self {
304 Value::Number(ref n) => n.as_u64(),
305 _ => None,
306 }
307 }
308
309 /// If the `Value` is a number, represent it as f64 if possible.
310 /// Returns None otherwise.
311 pub fn as_f64(&self) -> Option<f64> {
312 match *self {
313 Value::Number(ref n) => n.as_f64(),
314 _ => None,
315 }
316 }
317
318 /// Returns true if the `Value` is a Boolean. Returns false otherwise.
319 pub fn is_boolean(&self) -> bool {
320 self.as_bool().is_some()
321 }
322
323 /// If the `Value` is a Boolean, returns the associated bool.
324 /// Returns None otherwise.
325 pub fn as_bool(&self) -> Option<bool> {
326 match *self {
327 Value::Bool(b) => Some(b),
328 _ => None,
329 }
330 }
331
332 /// Returns true if the `Value` is a Null. Returns false otherwise.
333 pub fn is_null(&self) -> bool {
334 self.as_null().is_some()
335 }
336
337 /// If the `Value` is a Null, returns ().
338 /// Returns None otherwise.
339 pub fn as_null(&self) -> Option<()> {
340 match *self {
341 Value::Null => Some(()),
342 _ => None,
343 }
344 }
345
346 /// Looks up a value by a JSON Pointer.
347 ///
348 /// JSON Pointer defines a string syntax for identifying a specific value
349 /// within a JavaScript Object Notation (JSON) document.
350 ///
351 /// A Pointer is a Unicode string with the reference tokens separated by `/`.
352 /// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The
353 /// addressed value is returned and if there is no such value `None` is
354 /// returned.
355 ///
356 /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901).
357 ///
358 /// # Examples
359 ///
360 /// ```rust
361 /// # #[macro_use] extern crate serde_json;
362 /// # fn main() {
363 /// let data = json!({
364 /// "x": {
365 /// "y": ["z", "zz"]
366 /// }
367 /// });
368 ///
369 /// assert_eq!(data.pointer("/x/y/1").unwrap(), &json!("zz"));
370 /// assert_eq!(data.pointer("/a/b/c"), None);
371 /// # }
372 /// ```
373 pub fn pointer<'a>(&'a self, pointer: &str) -> Option<&'a Value> {
374 if pointer == "" {
375 return Some(self);
376 }
377 if !pointer.starts_with('/') {
378 return None;
379 }
380 let tokens = pointer.split('/').skip(1).map(|x| x.replace("~1", "/").replace("~0", "~"));
381 let mut target = self;
382
383 for token in tokens {
384 let target_opt = match *target {
385 Value::Object(ref map) => map.get(&token),
386 Value::Array(ref list) => parse_index(&token).and_then(|x| list.get(x)),
387 _ => return None,
388 };
389 if let Some(t) = target_opt {
390 target = t;
391 } else {
392 return None;
393 }
394 }
395 Some(target)
396 }
397
398 /// Looks up a value by a JSON Pointer and returns a mutable reference to
399 /// that value.
400 ///
401 /// JSON Pointer defines a string syntax for identifying a specific value
402 /// within a JavaScript Object Notation (JSON) document.
403 ///
404 /// A Pointer is a Unicode string with the reference tokens separated by `/`.
405 /// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The
406 /// addressed value is returned and if there is no such value `None` is
407 /// returned.
408 ///
409 /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901).
410 ///
411 /// # Example of Use
412 ///
413 /// ```rust
414 /// extern crate serde_json;
415 ///
416 /// use serde_json::Value;
417 /// use std::mem;
418 ///
419 /// fn main() {
420 /// let s = r#"{"x": 1.0, "y": 2.0}"#;
421 /// let mut value: Value = serde_json::from_str(s).unwrap();
422 ///
423 /// // Check value using read-only pointer
424 /// assert_eq!(value.pointer("/x"), Some(&1.0.into()));
425 /// // Change value with direct assignment
426 /// *value.pointer_mut("/x").unwrap() = 1.5.into();
427 /// // Check that new value was written
428 /// assert_eq!(value.pointer("/x"), Some(&1.5.into()));
429 ///
430 /// // "Steal" ownership of a value. Can replace with any valid Value.
431 /// let old_x = value.pointer_mut("/x").map(|x| mem::replace(x, Value::Null)).unwrap();
432 /// assert_eq!(old_x, 1.5);
433 /// assert_eq!(value.pointer("/x").unwrap(), &Value::Null);
434 /// }
435 /// ```
436 pub fn pointer_mut<'a>(&'a mut self, pointer: &str) -> Option<&'a mut Value> {
437 if pointer == "" {
438 return Some(self);
439 }
440 if !pointer.starts_with('/') {
441 return None;
442 }
443 let tokens = pointer.split('/').skip(1).map(|x| x.replace("~1", "/").replace("~0", "~"));
444 let mut target = self;
445
446 for token in tokens {
447 // borrow checker gets confused about `target` being mutably borrowed too many times because of the loop
448 // this once-per-loop binding makes the scope clearer and circumvents the error
449 let target_once = target;
450 let target_opt = match *target_once {
451 Value::Object(ref mut map) => map.get_mut(&token),
452 Value::Array(ref mut list) => parse_index(&token).and_then(move |x| list.get_mut(x)),
453 _ => return None,
454 };
455 if let Some(t) = target_opt {
456 target = t;
457 } else {
458 return None;
459 }
460 }
461 Some(target)
462 }
463 }
464
465 /// The default value is `Value::Null`.
466 ///
467 /// This is useful for handling omitted `Value` fields when deserializing.
468 ///
469 /// # Examples
470 ///
471 /// ```rust
472 /// # extern crate serde_json;
473 /// # #[macro_use] extern crate serde_derive;
474 /// use serde_json::Value;
475 ///
476 /// #[derive(Deserialize)]
477 /// struct Settings {
478 /// level: i32,
479 /// #[serde(default)]
480 /// extras: Value,
481 /// }
482 ///
483 /// # pub fn try_main() -> Result<(), serde_json::Error> {
484 /// let data = r#" { "level": 42 } "#;
485 /// let s: Settings = serde_json::from_str(data)?;
486 ///
487 /// assert_eq!(s.level, 42);
488 /// assert_eq!(s.extras, Value::Null);
489 /// # Ok(()) }
490 /// # fn main() { try_main().unwrap() }
491 /// ```
492 impl Default for Value {
493 fn default() -> Value {
494 Value::Null
495 }
496 }
497
498 /// A type that can be used to index into a `serde_json::Value`. See the `get`
499 /// and `get_mut` methods of `Value`.
500 ///
501 /// This trait is sealed and cannot be implemented for types outside of
502 /// `serde_json`.
503 pub trait Index: private::Sealed {
504 /// Return None if the key is not already in the array or object.
505 #[doc(hidden)]
506 fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value>;
507
508 /// Return None if the key is not already in the array or object.
509 #[doc(hidden)]
510 fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value>;
511
512 /// Panic if array index out of bounds. If key is not already in the object,
513 /// insert it with a value of null. Panic if Value is a type that cannot be
514 /// indexed into, except if Value is null then it can be treated as an empty
515 /// object.
516 #[doc(hidden)]
517 fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value;
518 }
519
520 impl Index for usize {
521 fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> {
522 match *v {
523 Value::Array(ref vec) => vec.get(*self),
524 _ => None,
525 }
526 }
527 fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> {
528 match *v {
529 Value::Array(ref mut vec) => vec.get_mut(*self),
530 _ => None,
531 }
532 }
533 fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value {
534 match *v {
535 Value::Array(ref mut vec) => {
536 let len = vec.len();
537 vec.get_mut(*self).unwrap_or_else(|| {
538 panic!("cannot access index {} of JSON array of length {}",
539 self, len)
540 })
541 }
542 _ => panic!("cannot access index {} of JSON {}", self, Type(v)),
543 }
544 }
545 }
546
547 impl Index for str {
548 fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> {
549 match *v {
550 Value::Object(ref map) => map.get(self),
551 _ => None,
552 }
553 }
554 fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> {
555 match *v {
556 Value::Object(ref mut map) => map.get_mut(self),
557 _ => None,
558 }
559 }
560 fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value {
561 if let Value::Null = *v {
562 let mut map = Map::new();
563 map.insert(self.to_owned(), Value::Null);
564 *v = Value::Object(map);
565 }
566 match *v {
567 Value::Object(ref mut map) => {
568 // TODO: use entry() once LinkedHashMap supports entry()
569 // https://github.com/contain-rs/linked-hash-map/issues/5
570 if !map.contains_key(self) {
571 map.insert(self.to_owned(), Value::Null);
572 }
573 map.get_mut(self).unwrap()
574 }
575 _ => panic!("cannot access key {:?} in JSON {}", self, Type(v)),
576 }
577 }
578 }
579
580 impl Index for String {
581 fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> {
582 self[..].index_into(v)
583 }
584 fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> {
585 self[..].index_into_mut(v)
586 }
587 fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value {
588 self[..].index_or_insert(v)
589 }
590 }
591
592 impl<'a, T: ?Sized> Index for &'a T where T: Index {
593 fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> {
594 (**self).index_into(v)
595 }
596 fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> {
597 (**self).index_into_mut(v)
598 }
599 fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value {
600 (**self).index_or_insert(v)
601 }
602 }
603
604 // Prevent users from implementing the Index trait.
605 mod private {
606 pub trait Sealed {}
607 impl Sealed for usize {}
608 impl Sealed for str {}
609 impl Sealed for String {}
610 impl<'a, T: ?Sized> Sealed for &'a T where T: Sealed {}
611 }
612
613 /// Used in panic messages.
614 struct Type<'a>(&'a Value);
615
616 impl<'a> fmt::Display for Type<'a> {
617 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
618 match *self.0 {
619 Value::Null => formatter.write_str("null"),
620 Value::Bool(_) => formatter.write_str("boolean"),
621 Value::Number(_) => formatter.write_str("number"),
622 Value::String(_) => formatter.write_str("string"),
623 Value::Array(_) => formatter.write_str("array"),
624 Value::Object(_) => formatter.write_str("object"),
625 }
626 }
627 }
628
629 // The usual semantics of Index is to panic on invalid indexing.
630 //
631 // That said, the usual semantics are for things like Vec and BTreeMap which
632 // have different use cases than Value. If you are working with a Vec, you know
633 // that you are working with a Vec and you can get the len of the Vec and make
634 // sure your indices are within bounds. The Value use cases are more
635 // loosey-goosey. You got some JSON from an endpoint and you want to pull values
636 // out of it. Outside of this Index impl, you already have the option of using
637 // value.as_array() and working with the Vec directly, or matching on
638 // Value::Array and getting the Vec directly. The Index impl means you can skip
639 // that and index directly into the thing using a concise syntax. You don't have
640 // to check the type, you don't have to check the len, it is all about what you
641 // expect the Value to look like.
642 //
643 // Basically the use cases that would be well served by panicking here are
644 // better served by using one of the other approaches: get and get_mut,
645 // as_array, or match. The value of this impl is that it adds a way of working
646 // with Value that is not well served by the existing approaches: concise and
647 // careless and sometimes that is exactly what you want.
648 impl<I> ops::Index<I> for Value where I: Index {
649 type Output = Value;
650
651 /// Index into a `serde_json::Value` using the syntax `value[0]` or
652 /// `value["k"]`.
653 ///
654 /// Returns `Value::Null` if the type of `self` does not match the type of
655 /// the index, for example if the index is a string and `self` is an array
656 /// or a number. Also returns `Value::Null` if the given key does not exist
657 /// in the map or the given index is not within the bounds of the array.
658 ///
659 /// For retrieving deeply nested values, you should have a look at the
660 /// `Value::pointer` method.
661 ///
662 /// # Examples
663 ///
664 /// ```rust
665 /// # #[macro_use] extern crate serde_json;
666 /// # fn main() {
667 /// let data = json!({
668 /// "x": {
669 /// "y": ["z", "zz"]
670 /// }
671 /// });
672 ///
673 /// assert_eq!(data["x"]["y"], json!(["z", "zz"]));
674 /// assert_eq!(data["x"]["y"][0], json!("z"));
675 ///
676 /// assert_eq!(data["a"], json!(null)); // returns null for undefined values
677 /// assert_eq!(data["a"]["b"], json!(null)); // does not panic
678 /// # }
679 /// ```
680 fn index(&self, index: I) -> &Value {
681 static NULL: Value = Value::Null;
682 index.index_into(self).unwrap_or(&NULL)
683 }
684 }
685
686 impl<I> ops::IndexMut<I> for Value where I: Index {
687 /// Write into a `serde_json::Value` using the syntax `value[0] = ...` or
688 /// `value["k"] = ...`.
689 ///
690 /// If the index is a number, the value must be an array of length bigger
691 /// than the index. Indexing into a value that is not an array or an array
692 /// that is too small will panic.
693 ///
694 /// If the index is a string, the value must be an object or null which is
695 /// treated like an empty object. If the key is not already present in the
696 /// object, it will be inserted with a value of null. Indexing into a value
697 /// that is neither an object nor null will panic.
698 ///
699 /// # Examples
700 ///
701 /// ```rust
702 /// # #[macro_use] extern crate serde_json;
703 /// # fn main() {
704 /// let mut data = json!({ "x": 0 });
705 ///
706 /// // replace an existing key
707 /// data["x"] = json!(1);
708 ///
709 /// // insert a new key
710 /// data["y"] = json!([false, false, false]);
711 ///
712 /// // replace an array value
713 /// data["y"][0] = json!(true);
714 ///
715 /// // inserted a deeply nested key
716 /// data["a"]["b"]["c"]["d"] = json!(true);
717 ///
718 /// println!("{}", data);
719 /// # }
720 /// ```
721 fn index_mut(&mut self, index: I) -> &mut Value {
722 index.index_or_insert(self)
723 }
724 }
725
726 impl PartialEq<str> for Value {
727 fn eq(&self, other: &str) -> bool {
728 self.as_str().map_or(false, |s| s == other)
729 }
730 }
731
732 impl<'a> PartialEq<&'a str> for Value {
733 fn eq(&self, other: &&str) -> bool {
734 self.as_str().map_or(false, |s| s == *other)
735 }
736 }
737
738 impl PartialEq<Value> for str {
739 fn eq(&self, other: &Value) -> bool {
740 other.as_str().map_or(false, |s| s == self)
741 }
742 }
743
744 impl<'a> PartialEq<Value> for &'a str {
745 fn eq(&self, other: &Value) -> bool {
746 other.as_str().map_or(false, |s| s == *self)
747 }
748 }
749
750 impl PartialEq<String> for Value {
751 fn eq(&self, other: &String) -> bool {
752 self.as_str().map_or(false, |s| s == other)
753 }
754 }
755
756
757 impl PartialEq<Value> for String {
758 fn eq(&self, other: &Value) -> bool {
759 other.as_str().map_or(false, |s| s == self)
760 }
761 }
762
763 macro_rules! partialeq_numeric {
764 ($([$($ty:ty)*], $conversion:ident, $base:ty)*) => {
765 $($(
766 impl PartialEq<$ty> for Value {
767 fn eq(&self, other: &$ty) -> bool {
768 self.$conversion().map_or(false, |i| i == (*other as $base))
769 }
770 }
771
772 impl PartialEq<Value> for $ty {
773 fn eq(&self, other: &Value) -> bool {
774 other.$conversion().map_or(false, |i| i == (*self as $base))
775 }
776 }
777
778 impl<'a> PartialEq<$ty> for &'a Value {
779 fn eq(&self, other: &$ty) -> bool {
780 self.$conversion().map_or(false, |i| i == (*other as $base))
781 }
782 }
783
784 impl<'a> PartialEq<$ty> for &'a mut Value {
785 fn eq(&self, other: &$ty) -> bool {
786 self.$conversion().map_or(false, |i| i == (*other as $base))
787 }
788 }
789 )*)*
790 }
791 }
792
793 partialeq_numeric! {
794 [i8 i16 i32 i64 isize], as_i64, i64
795 [u8 u16 u32 u64 usize], as_u64, u64
796 [f32 f64], as_f64, f64
797 }
798
799 macro_rules! from_integer {
800 ($($ty:ident)*) => {
801 $(
802 impl From<$ty> for Value {
803 fn from(n: $ty) -> Self {
804 Value::Number(n.into())
805 }
806 }
807 )*
808 };
809 }
810
811 from_integer! {
812 i8 i16 i32 i64 isize
813 u8 u16 u32 u64 usize
814 }
815
816 impl From<f32> for Value {
817 /// Convert 32-bit floating point number to `Value`
818 ///
819 /// # Examples
820 ///
821 /// ```rust
822 /// # extern crate serde_json;
823 /// use serde_json::Value;
824 ///
825 /// # fn main() {
826 /// let f: f32 = 13.37;
827 /// let x: Value = f.into();
828 /// # }
829 /// ```
830 fn from(f: f32) -> Self {
831 From::from(f as f64)
832 }
833 }
834
835 impl From<f64> for Value {
836 /// Convert 64-bit floating point number to `Value`
837 ///
838 /// # Examples
839 ///
840 /// ```rust
841 /// # extern crate serde_json;
842 /// use serde_json::Value;
843 ///
844 /// # fn main() {
845 /// let f: f64 = 13.37;
846 /// let x: Value = f.into();
847 /// # }
848 /// ```
849 fn from(f: f64) -> Self {
850 Number::from_f64(f).map_or(Value::Null, Value::Number)
851 }
852 }
853
854 impl From<bool> for Value {
855 /// Convert boolean to `Value`
856 ///
857 /// # Examples
858 ///
859 /// ```rust
860 /// # extern crate serde_json;
861 /// use serde_json::Value;
862 ///
863 /// # fn main() {
864 /// let b = false;
865 /// let x: Value = b.into();
866 /// # }
867 /// ```
868 fn from(f: bool) -> Self {
869 Value::Bool(f)
870 }
871 }
872
873 impl From<String> for Value {
874 /// Convert `String` to `Value`
875 ///
876 /// # Examples
877 ///
878 /// ```rust
879 /// # extern crate serde_json;
880 /// use serde_json::Value;
881 ///
882 /// # fn main() {
883 /// let s: String = "lorem".to_string();
884 /// let x: Value = s.into();
885 /// # }
886 /// ```
887 fn from(f: String) -> Self {
888 Value::String(f)
889 }
890 }
891
892 impl<'a> From<&'a str> for Value {
893 /// Convert string slice to `Value`
894 ///
895 /// # Examples
896 ///
897 /// ```rust
898 /// # extern crate serde_json;
899 /// use serde_json::Value;
900 ///
901 /// # fn main() {
902 /// let s: &str = "lorem";
903 /// let x: Value = s.into();
904 /// # }
905 /// ```
906 fn from(f: &str) -> Self {
907 Value::String(f.to_string())
908 }
909 }
910
911 impl<'a> From<Cow<'a, str>> for Value {
912 /// Convert copy-on-write string to `Value`
913 ///
914 /// # Examples
915 ///
916 /// ```rust
917 /// # extern crate serde_json;
918 /// use serde_json::Value;
919 /// use std::borrow::Cow;
920 /// # fn main() {
921 ///
922 /// let s: Cow<str> = Cow::Borrowed("lorem");
923 /// let x: Value = s.into();
924 /// # }
925 /// ```
926 ///
927 /// ```rust
928 /// # extern crate serde_json;
929 /// use serde_json::Value;
930 /// use std::borrow::Cow;
931 ///
932 /// # fn main() {
933 /// let s: Cow<str> = Cow::Owned("lorem".to_string());
934 /// let x: Value = s.into();
935 /// # }
936 /// ```
937 fn from(f: Cow<'a, str>) -> Self {
938 Value::String(f.to_string())
939 }
940 }
941
942 impl From<Map<String, Value>> for Value {
943 /// Convert map (with string keys) to `Value`
944 ///
945 /// # Examples
946 ///
947 /// ```rust
948 /// # extern crate serde_json;
949 /// use serde_json::{Map, Value};
950 /// # fn main() {
951 ///
952 /// let mut m = Map::new();
953 /// m.insert("Lorem".to_string(), "ipsum".into());
954 /// let x: Value = m.into();
955 /// # }
956 /// ```
957 fn from(f: Map<String, Value>) -> Self {
958 Value::Object(f)
959 }
960 }
961
962 impl<T: Into<Value>> From<Vec<T>> for Value {
963 /// Convert a `Vec` to `Value`
964 ///
965 /// # Examples
966 ///
967 /// ```rust
968 /// # extern crate serde_json;
969 /// use serde_json::Value;
970 /// # fn main() {
971 ///
972 /// let v = vec!["lorem", "ipsum", "dolor"];
973 /// let x: Value = v.into();
974 /// # }
975 /// ```
976 fn from(f: Vec<T>) -> Self {
977 Value::Array(f.into_iter().map(Into::into).collect())
978 }
979 }
980
981 impl<'a, T: Clone + Into<Value>> From<&'a [T]> for Value {
982 /// Convert a slice to `Value`
983 ///
984 /// # Examples
985 ///
986 /// ```rust
987 /// # extern crate serde_json;
988 /// use serde_json::Value;
989 /// # fn main() {
990 ///
991 /// let v: &[&str] = &["lorem", "ipsum", "dolor"];
992 /// let x: Value = v.into();
993 /// # }
994 /// ```
995 fn from(f: &'a [T]) -> Self {
996 Value::Array(f.into_iter().cloned().map(Into::into).collect())
997 }
998 }
999
1000 impl<T: Into<Value>> ::std::iter::FromIterator<T> for Value {
1001 /// Convert an iteratable type to a `Value`
1002 ///
1003 /// # Examples
1004 ///
1005 /// ```rust
1006 /// # extern crate serde_json;
1007 /// use serde_json::Value;
1008 /// # fn main() {
1009 ///
1010 /// let v = std::iter::repeat(42).take(5);
1011 /// let x: Value = v.collect();
1012 /// # }
1013 /// ```
1014 ///
1015 /// ```rust
1016 /// # extern crate serde_json;
1017 /// use serde_json::Value;
1018 ///
1019 /// # fn main() {
1020 /// let v: Vec<_> = vec!["lorem", "ipsum", "dolor"];
1021 /// let x: Value = v.into_iter().collect();
1022 /// # }
1023 /// ```
1024 ///
1025 /// ```rust
1026 /// # extern crate serde_json;
1027 /// use std::iter::FromIterator;
1028 /// use serde_json::Value;
1029 ///
1030 /// # fn main() {
1031 /// let x: Value = Value::from_iter(vec!["lorem", "ipsum", "dolor"]);
1032 /// # }
1033 /// ```
1034 fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> Self {
1035 let vec: Vec<Value> = iter.into_iter().map(|x| x.into()).collect();
1036
1037 Value::Array(vec)
1038 }
1039 }
1040
1041 impl ser::Serialize for Value {
1042 #[inline]
1043 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1044 where S: ser::Serializer,
1045 {
1046 match *self {
1047 Value::Null => serializer.serialize_unit(),
1048 Value::Bool(b) => serializer.serialize_bool(b),
1049 Value::Number(ref n) => n.serialize(serializer),
1050 Value::String(ref s) => serializer.serialize_str(s),
1051 Value::Array(ref v) => v.serialize(serializer),
1052 Value::Object(ref m) => {
1053 use serde::ser::SerializeMap;
1054 let mut map = try!(serializer.serialize_map(Some(m.len())));
1055 for (k, v) in m {
1056 try!(map.serialize_key(k));
1057 try!(map.serialize_value(v));
1058 }
1059 map.end()
1060 }
1061 }
1062 }
1063 }
1064
1065 impl de::Deserialize for Value {
1066 #[inline]
1067 fn deserialize<D>(deserializer: D) -> Result<Value, D::Error>
1068 where D: de::Deserializer,
1069 {
1070 struct ValueVisitor;
1071
1072 impl de::Visitor for ValueVisitor {
1073 type Value = Value;
1074
1075 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1076 formatter.write_str("any valid JSON value")
1077 }
1078
1079 #[inline]
1080 fn visit_bool<E>(self, value: bool) -> Result<Value, E> {
1081 Ok(Value::Bool(value))
1082 }
1083
1084 #[inline]
1085 fn visit_i64<E>(self, value: i64) -> Result<Value, E> {
1086 Ok(Value::Number(value.into()))
1087 }
1088
1089 #[inline]
1090 fn visit_u64<E>(self, value: u64) -> Result<Value, E> {
1091 Ok(Value::Number(value.into()))
1092 }
1093
1094 #[inline]
1095 fn visit_f64<E>(self, value: f64) -> Result<Value, E> {
1096 Ok(Number::from_f64(value).map_or(Value::Null, Value::Number))
1097 }
1098
1099 #[inline]
1100 fn visit_str<E>(self, value: &str) -> Result<Value, E>
1101 where E: de::Error,
1102 {
1103 self.visit_string(String::from(value))
1104 }
1105
1106 #[inline]
1107 fn visit_string<E>(self, value: String) -> Result<Value, E> {
1108 Ok(Value::String(value))
1109 }
1110
1111 #[inline]
1112 fn visit_none<E>(self) -> Result<Value, E> {
1113 Ok(Value::Null)
1114 }
1115
1116 #[inline]
1117 fn visit_some<D>(
1118 self,
1119 deserializer: D
1120 ) -> Result<Value, D::Error>
1121 where D: de::Deserializer,
1122 {
1123 de::Deserialize::deserialize(deserializer)
1124 }
1125
1126 #[inline]
1127 fn visit_unit<E>(self) -> Result<Value, E> {
1128 Ok(Value::Null)
1129 }
1130
1131 #[inline]
1132 fn visit_seq<V>(self, visitor: V) -> Result<Value, V::Error>
1133 where V: de::SeqVisitor,
1134 {
1135 let values = try!(de::impls::VecVisitor::new()
1136 .visit_seq(visitor));
1137 Ok(Value::Array(values))
1138 }
1139
1140 fn visit_map<V>(self, mut visitor: V) -> Result<Value, V::Error>
1141 where V: de::MapVisitor,
1142 {
1143 let mut values = Map::with_capacity(visitor.size_hint().0);
1144
1145 while let Some((key, value)) = try!(visitor.visit()) {
1146 values.insert(key, value);
1147 }
1148
1149 Ok(Value::Object(values))
1150 }
1151 }
1152
1153 deserializer.deserialize(ValueVisitor)
1154 }
1155 }
1156
1157 struct WriterFormatter<'a, 'b: 'a> {
1158 inner: &'a mut fmt::Formatter<'b>,
1159 }
1160
1161 impl<'a, 'b> io::Write for WriterFormatter<'a, 'b> {
1162 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1163 fn io_error<E>(_: E) -> io::Error {
1164 // Value does not matter because fmt::Debug and fmt::Display impls
1165 // below just map it to fmt::Error
1166 io::Error::new(io::ErrorKind::Other, "fmt error")
1167 }
1168 let s = try!(str::from_utf8(buf).map_err(io_error));
1169 try!(self.inner.write_str(s).map_err(io_error));
1170 Ok(buf.len())
1171 }
1172
1173 fn flush(&mut self) -> io::Result<()> {
1174 Ok(())
1175 }
1176 }
1177
1178 impl fmt::Display for Value {
1179 /// Serializes a json value into a string
1180 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1181 let mut wr = WriterFormatter {
1182 inner: f,
1183 };
1184 super::ser::to_writer(&mut wr, self).map_err(|_| fmt::Error)
1185 }
1186 }
1187
1188 impl str::FromStr for Value {
1189 type Err = Error;
1190 fn from_str(s: &str) -> Result<Value, Error> {
1191 super::de::from_str(s)
1192 }
1193 }
1194
1195 struct Serializer;
1196
1197 impl ser::Serializer for Serializer {
1198 type Ok = Value;
1199 type Error = Error;
1200
1201 type SerializeSeq = SerializeVec;
1202 type SerializeTuple = SerializeVec;
1203 type SerializeTupleStruct = SerializeVec;
1204 type SerializeTupleVariant = SerializeTupleVariant;
1205 type SerializeMap = SerializeMap;
1206 type SerializeStruct = SerializeMap;
1207 type SerializeStructVariant = SerializeStructVariant;
1208
1209 #[inline]
1210 fn serialize_bool(self, value: bool) -> Result<Value, Error> {
1211 Ok(Value::Bool(value))
1212 }
1213
1214 #[inline]
1215 fn serialize_i8(self, value: i8) -> Result<Value, Error> {
1216 self.serialize_i64(value as i64)
1217 }
1218
1219 #[inline]
1220 fn serialize_i16(self, value: i16) -> Result<Value, Error> {
1221 self.serialize_i64(value as i64)
1222 }
1223
1224 #[inline]
1225 fn serialize_i32(self, value: i32) -> Result<Value, Error> {
1226 self.serialize_i64(value as i64)
1227 }
1228
1229 fn serialize_i64(self, value: i64) -> Result<Value, Error> {
1230 Ok(Value::Number(value.into()))
1231 }
1232
1233 #[inline]
1234 fn serialize_u8(self, value: u8) -> Result<Value, Error> {
1235 self.serialize_u64(value as u64)
1236 }
1237
1238 #[inline]
1239 fn serialize_u16(self, value: u16) -> Result<Value, Error> {
1240 self.serialize_u64(value as u64)
1241 }
1242
1243 #[inline]
1244 fn serialize_u32(self, value: u32) -> Result<Value, Error> {
1245 self.serialize_u64(value as u64)
1246 }
1247
1248 #[inline]
1249 fn serialize_u64(self, value: u64) -> Result<Value, Error> {
1250 Ok(Value::Number(value.into()))
1251 }
1252
1253 #[inline]
1254 fn serialize_f32(self, value: f32) -> Result<Value, Error> {
1255 self.serialize_f64(value as f64)
1256 }
1257
1258 #[inline]
1259 fn serialize_f64(self, value: f64) -> Result<Value, Error> {
1260 Ok(Number::from_f64(value).map_or(Value::Null, Value::Number))
1261 }
1262
1263 #[inline]
1264 fn serialize_char(self, value: char) -> Result<Value, Error> {
1265 let mut s = String::new();
1266 s.push(value);
1267 self.serialize_str(&s)
1268 }
1269
1270 #[inline]
1271 fn serialize_str(self, value: &str) -> Result<Value, Error> {
1272 Ok(Value::String(value.to_owned()))
1273 }
1274
1275 fn serialize_bytes(self, value: &[u8]) -> Result<Value, Error> {
1276 let vec = value.iter().map(|&b| Value::Number(b.into())).collect();
1277 Ok(Value::Array(vec))
1278 }
1279
1280 #[inline]
1281 fn serialize_unit(self) -> Result<Value, Error> {
1282 Ok(Value::Null)
1283 }
1284
1285 #[inline]
1286 fn serialize_unit_struct(
1287 self,
1288 _name: &'static str
1289 ) -> Result<Value, Error> {
1290 self.serialize_unit()
1291 }
1292
1293 #[inline]
1294 fn serialize_unit_variant(
1295 self,
1296 _name: &'static str,
1297 _variant_index: usize,
1298 variant: &'static str
1299 ) -> Result<Value, Error> {
1300 self.serialize_str(variant)
1301 }
1302
1303 #[inline]
1304 fn serialize_newtype_struct<T: ?Sized>(
1305 self,
1306 _name: &'static str,
1307 value: &T
1308 ) -> Result<Value, Error>
1309 where T: ser::Serialize,
1310 {
1311 value.serialize(self)
1312 }
1313
1314 fn serialize_newtype_variant<T: ?Sized>(
1315 self,
1316 _name: &'static str,
1317 _variant_index: usize,
1318 variant: &'static str,
1319 value: &T
1320 ) -> Result<Value, Error>
1321 where T: ser::Serialize,
1322 {
1323 let mut values = Map::new();
1324 values.insert(String::from(variant), try!(to_value(&value)));
1325 Ok(Value::Object(values))
1326 }
1327
1328 #[inline]
1329 fn serialize_none(self) -> Result<Value, Error> {
1330 self.serialize_unit()
1331 }
1332
1333 #[inline]
1334 fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Value, Error>
1335 where T: ser::Serialize,
1336 {
1337 value.serialize(self)
1338 }
1339
1340 fn serialize_seq(
1341 self,
1342 len: Option<usize>
1343 ) -> Result<Self::SerializeSeq, Error> {
1344 Ok(SerializeVec {
1345 vec: Vec::with_capacity(len.unwrap_or(0))
1346 })
1347 }
1348
1349 fn serialize_seq_fixed_size(
1350 self,
1351 size: usize
1352 ) -> Result<Self::SerializeSeq, Error> {
1353 self.serialize_seq(Some(size))
1354 }
1355
1356 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Error> {
1357 self.serialize_seq(Some(len))
1358 }
1359
1360 fn serialize_tuple_struct(
1361 self,
1362 _name: &'static str,
1363 len: usize
1364 ) -> Result<Self::SerializeTupleStruct, Error> {
1365 self.serialize_seq(Some(len))
1366 }
1367
1368 fn serialize_tuple_variant(
1369 self,
1370 _name: &'static str,
1371 _variant_index: usize,
1372 variant: &'static str,
1373 len: usize
1374 ) -> Result<Self::SerializeTupleVariant, Error> {
1375 Ok(SerializeTupleVariant {
1376 name: String::from(variant),
1377 vec: Vec::with_capacity(len),
1378 })
1379 }
1380
1381 fn serialize_map(
1382 self,
1383 _len: Option<usize>
1384 ) -> Result<Self::SerializeMap, Error> {
1385 Ok(SerializeMap {
1386 map: Map::new(),
1387 next_key: None,
1388 })
1389 }
1390
1391 fn serialize_struct(
1392 self,
1393 _name: &'static str,
1394 len: usize
1395 ) -> Result<Self::SerializeStruct, Error> {
1396 self.serialize_map(Some(len))
1397 }
1398
1399 fn serialize_struct_variant(
1400 self,
1401 _name: &'static str,
1402 _variant_index: usize,
1403 variant: &'static str,
1404 _len: usize
1405 ) -> Result<Self::SerializeStructVariant, Error> {
1406 Ok(SerializeStructVariant {
1407 name: String::from(variant),
1408 map: Map::new(),
1409 })
1410 }
1411 }
1412
1413 #[doc(hidden)]
1414 pub struct SerializeVec {
1415 vec: Vec<Value>,
1416 }
1417
1418 #[doc(hidden)]
1419 pub struct SerializeTupleVariant {
1420 name: String,
1421 vec: Vec<Value>,
1422 }
1423
1424 #[doc(hidden)]
1425 pub struct SerializeMap {
1426 map: Map<String, Value>,
1427 next_key: Option<String>,
1428 }
1429
1430 #[doc(hidden)]
1431 pub struct SerializeStructVariant {
1432 name: String,
1433 map: Map<String, Value>,
1434 }
1435
1436 impl ser::SerializeSeq for SerializeVec {
1437 type Ok = Value;
1438 type Error = Error;
1439
1440 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
1441 where T: ser::Serialize
1442 {
1443 self.vec.push(try!(to_value(&value)));
1444 Ok(())
1445 }
1446
1447 fn end(self) -> Result<Value, Error> {
1448 Ok(Value::Array(self.vec))
1449 }
1450 }
1451
1452 impl ser::SerializeTuple for SerializeVec {
1453 type Ok = Value;
1454 type Error = Error;
1455
1456 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
1457 where T: ser::Serialize
1458 {
1459 ser::SerializeSeq::serialize_element(self, value)
1460 }
1461
1462 fn end(self) -> Result<Value, Error> {
1463 ser::SerializeSeq::end(self)
1464 }
1465 }
1466
1467 impl ser::SerializeTupleStruct for SerializeVec {
1468 type Ok = Value;
1469 type Error = Error;
1470
1471 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
1472 where T: ser::Serialize
1473 {
1474 ser::SerializeSeq::serialize_element(self, value)
1475 }
1476
1477 fn end(self) -> Result<Value, Error> {
1478 ser::SerializeSeq::end(self)
1479 }
1480 }
1481
1482 impl ser::SerializeTupleVariant for SerializeTupleVariant {
1483 type Ok = Value;
1484 type Error = Error;
1485
1486 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
1487 where T: ser::Serialize
1488 {
1489 self.vec.push(try!(to_value(&value)));
1490 Ok(())
1491 }
1492
1493 fn end(self) -> Result<Value, Error> {
1494 let mut object = Map::new();
1495
1496 object.insert(self.name, Value::Array(self.vec));
1497
1498 Ok(Value::Object(object))
1499 }
1500 }
1501
1502 impl ser::SerializeMap for SerializeMap {
1503 type Ok = Value;
1504 type Error = Error;
1505
1506 fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Error>
1507 where T: ser::Serialize
1508 {
1509 match try!(to_value(&key)) {
1510 Value::String(s) => self.next_key = Some(s),
1511 Value::Number(n) => {
1512 if n.is_u64() || n.is_i64() {
1513 self.next_key = Some(n.to_string())
1514 } else {
1515 return Err(Error::syntax(ErrorCode::KeyMustBeAString, 0, 0))
1516 }
1517 }
1518 _ => return Err(Error::syntax(ErrorCode::KeyMustBeAString, 0, 0)),
1519 };
1520 Ok(())
1521 }
1522
1523 fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
1524 where T: ser::Serialize
1525 {
1526 let key = self.next_key.take();
1527 // Panic because this indicates a bug in the program rather than an
1528 // expected failure.
1529 let key = key.expect("serialize_value called before serialize_key");
1530 self.map.insert(key, try!(to_value(&value)));
1531 Ok(())
1532 }
1533
1534 fn end(self) -> Result<Value, Error> {
1535 Ok(Value::Object(self.map))
1536 }
1537 }
1538
1539 impl ser::SerializeStruct for SerializeMap {
1540 type Ok = Value;
1541 type Error = Error;
1542
1543 fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
1544 where T: ser::Serialize
1545 {
1546 try!(ser::SerializeMap::serialize_key(self, key));
1547 ser::SerializeMap::serialize_value(self, value)
1548 }
1549
1550 fn end(self) -> Result<Value, Error> {
1551 ser::SerializeMap::end(self)
1552 }
1553 }
1554
1555 impl ser::SerializeStructVariant for SerializeStructVariant {
1556 type Ok = Value;
1557 type Error = Error;
1558
1559 fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
1560 where T: ser::Serialize
1561 {
1562 self.map.insert(String::from(key), try!(to_value(&value)));
1563 Ok(())
1564 }
1565
1566 fn end(self) -> Result<Value, Error> {
1567 let mut object = Map::new();
1568
1569 object.insert(self.name, Value::Object(self.map));
1570
1571 Ok(Value::Object(object))
1572 }
1573 }
1574
1575 impl de::Deserializer for Value {
1576 type Error = Error;
1577
1578 #[inline]
1579 fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
1580 where V: de::Visitor,
1581 {
1582 match self {
1583 Value::Null => visitor.visit_unit(),
1584 Value::Bool(v) => visitor.visit_bool(v),
1585 Value::Number(n) => n.deserialize(visitor),
1586 Value::String(v) => visitor.visit_string(v),
1587 Value::Array(v) => {
1588 let len = v.len();
1589 let mut deserializer = SeqDeserializer::new(v);
1590 let seq = try!(visitor.visit_seq(&mut deserializer));
1591 let remaining = deserializer.iter.len();
1592 if remaining == 0 {
1593 Ok(seq)
1594 } else {
1595 Err(de::Error::invalid_length(len, &"fewer elements in array"))
1596 }
1597 }
1598 Value::Object(v) => {
1599 let len = v.len();
1600 let mut deserializer = MapDeserializer::new(v);
1601 let map = try!(visitor.visit_map(&mut deserializer));
1602 let remaining = deserializer.iter.len();
1603 if remaining == 0 {
1604 Ok(map)
1605 } else {
1606 Err(de::Error::invalid_length(len, &"fewer elements in map"))
1607 }
1608 }
1609 }
1610 }
1611
1612 #[inline]
1613 fn deserialize_option<V>(
1614 self,
1615 visitor: V
1616 ) -> Result<V::Value, Error>
1617 where V: de::Visitor,
1618 {
1619 match self {
1620 Value::Null => visitor.visit_none(),
1621 _ => visitor.visit_some(self),
1622 }
1623 }
1624
1625 #[inline]
1626 fn deserialize_enum<V>(
1627 self,
1628 _name: &str,
1629 _variants: &'static [&'static str],
1630 visitor: V
1631 ) -> Result<V::Value, Error>
1632 where V: de::Visitor,
1633 {
1634 let (variant, value) = match self {
1635 Value::Object(value) => {
1636 let mut iter = value.into_iter();
1637 let (variant, value) = match iter.next() {
1638 Some(v) => v,
1639 None => {
1640 return Err(de::Error::invalid_value(Unexpected::Map, &"map with a single key"));
1641 }
1642 };
1643 // enums are encoded in json as maps with a single key:value pair
1644 if iter.next().is_some() {
1645 return Err(de::Error::invalid_value(Unexpected::Map, &"map with a single key"));
1646 }
1647 (variant, Some(value))
1648 }
1649 Value::String(variant) => (variant, None),
1650 other => {
1651 return Err(de::Error::invalid_type(other.unexpected(), &"string or map"));
1652 }
1653 };
1654
1655 visitor.visit_enum(EnumDeserializer {
1656 variant: variant,
1657 value: value,
1658 })
1659 }
1660
1661 #[inline]
1662 fn deserialize_newtype_struct<V>(
1663 self,
1664 _name: &'static str,
1665 visitor: V
1666 ) -> Result<V::Value, Self::Error>
1667 where V: de::Visitor,
1668 {
1669 visitor.visit_newtype_struct(self)
1670 }
1671
1672 forward_to_deserialize! {
1673 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
1674 seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct
1675 struct_field tuple ignored_any
1676 }
1677 }
1678
1679 struct EnumDeserializer {
1680 variant: String,
1681 value: Option<Value>,
1682 }
1683
1684 impl de::EnumVisitor for EnumDeserializer {
1685 type Error = Error;
1686 type Variant = VariantDeserializer;
1687
1688 fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, VariantDeserializer), Error>
1689 where V: de::DeserializeSeed,
1690 {
1691 let variant = self.variant.into_deserializer();
1692 let visitor = VariantDeserializer { value: self.value };
1693 seed.deserialize(variant).map(|v| (v, visitor))
1694 }
1695 }
1696
1697 struct VariantDeserializer {
1698 value: Option<Value>,
1699 }
1700
1701 impl de::VariantVisitor for VariantDeserializer {
1702 type Error = Error;
1703
1704 fn visit_unit(self) -> Result<(), Error> {
1705 match self.value {
1706 Some(value) => de::Deserialize::deserialize(value),
1707 None => Ok(()),
1708 }
1709 }
1710
1711 fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value, Error>
1712 where T: de::DeserializeSeed,
1713 {
1714 match self.value {
1715 Some(value) => seed.deserialize(value),
1716 None => Err(de::Error::invalid_type(Unexpected::UnitVariant, &"newtype variant")),
1717 }
1718 }
1719
1720 fn visit_tuple<V>(
1721 self,
1722 _len: usize,
1723 visitor: V
1724 ) -> Result<V::Value, Error>
1725 where V: de::Visitor,
1726 {
1727 match self.value {
1728 Some(Value::Array(v)) => {
1729 de::Deserializer::deserialize(SeqDeserializer::new(v), visitor)
1730 }
1731 Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"tuple variant")),
1732 None => Err(de::Error::invalid_type(Unexpected::UnitVariant, &"tuple variant"))
1733 }
1734 }
1735
1736 fn visit_struct<V>(
1737 self,
1738 _fields: &'static [&'static str],
1739 visitor: V
1740 ) -> Result<V::Value, Error>
1741 where V: de::Visitor,
1742 {
1743 match self.value {
1744 Some(Value::Object(v)) => {
1745 de::Deserializer::deserialize(MapDeserializer::new(v), visitor)
1746 }
1747 Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"struct variant")),
1748 _ => Err(de::Error::invalid_type(Unexpected::UnitVariant, &"struct variant"))
1749 }
1750 }
1751 }
1752
1753 struct SeqDeserializer {
1754 iter: vec::IntoIter<Value>,
1755 }
1756
1757 impl SeqDeserializer {
1758 fn new(vec: Vec<Value>) -> Self {
1759 SeqDeserializer {
1760 iter: vec.into_iter(),
1761 }
1762 }
1763 }
1764
1765 impl de::Deserializer for SeqDeserializer {
1766 type Error = Error;
1767
1768 #[inline]
1769 fn deserialize<V>(mut self, visitor: V) -> Result<V::Value, Error>
1770 where V: de::Visitor,
1771 {
1772 let len = self.iter.len();
1773 if len == 0 {
1774 visitor.visit_unit()
1775 } else {
1776 let ret = try!(visitor.visit_seq(&mut self));
1777 let remaining = self.iter.len();
1778 if remaining == 0 {
1779 Ok(ret)
1780 } else {
1781 Err(de::Error::invalid_length(len, &"fewer elements in array"))
1782 }
1783 }
1784 }
1785
1786 forward_to_deserialize! {
1787 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
1788 seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
1789 tuple_struct struct struct_field tuple enum ignored_any
1790 }
1791 }
1792
1793 impl de::SeqVisitor for SeqDeserializer {
1794 type Error = Error;
1795
1796 fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
1797 where T: de::DeserializeSeed,
1798 {
1799 match self.iter.next() {
1800 Some(value) => seed.deserialize(value).map(Some),
1801 None => Ok(None),
1802 }
1803 }
1804
1805 fn size_hint(&self) -> (usize, Option<usize>) {
1806 self.iter.size_hint()
1807 }
1808 }
1809
1810 struct MapDeserializer {
1811 iter: <Map<String, Value> as IntoIterator>::IntoIter,
1812 value: Option<Value>,
1813 }
1814
1815 impl MapDeserializer {
1816 fn new(map: Map<String, Value>) -> Self {
1817 MapDeserializer {
1818 iter: map.into_iter(),
1819 value: None,
1820 }
1821 }
1822 }
1823
1824 impl de::MapVisitor for MapDeserializer {
1825 type Error = Error;
1826
1827 fn visit_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
1828 where T: de::DeserializeSeed,
1829 {
1830 match self.iter.next() {
1831 Some((key, value)) => {
1832 self.value = Some(value);
1833 seed.deserialize(key.into_deserializer()).map(Some)
1834 }
1835 None => Ok(None),
1836 }
1837 }
1838
1839 fn visit_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Error>
1840 where T: de::DeserializeSeed,
1841 {
1842 match self.value.take() {
1843 Some(value) => seed.deserialize(value),
1844 None => Err(de::Error::custom("value is missing")),
1845 }
1846 }
1847
1848 fn size_hint(&self) -> (usize, Option<usize>) {
1849 self.iter.size_hint()
1850 }
1851 }
1852
1853 impl de::Deserializer for MapDeserializer {
1854 type Error = Error;
1855
1856 #[inline]
1857 fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
1858 where V: de::Visitor,
1859 {
1860 visitor.visit_map(self)
1861 }
1862
1863 forward_to_deserialize! {
1864 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
1865 seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
1866 tuple_struct struct struct_field tuple enum ignored_any
1867 }
1868 }
1869
1870 impl<'a> de::Deserializer for &'a Value {
1871 type Error = Error;
1872
1873 fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
1874 where V: de::Visitor,
1875 {
1876 match *self {
1877 Value::Null => visitor.visit_unit(),
1878 Value::Bool(v) => visitor.visit_bool(v),
1879 Value::Number(ref n) => n.deserialize(visitor),
1880 Value::String(ref v) => visitor.visit_str(v),
1881 Value::Array(ref v) => {
1882 let len = v.len();
1883 let mut deserializer = SeqRefDeserializer::new(v);
1884 let seq = try!(visitor.visit_seq(&mut deserializer));
1885 let remaining = deserializer.iter.len();
1886 if remaining == 0 {
1887 Ok(seq)
1888 } else {
1889 Err(de::Error::invalid_length(len, &"fewer elements in array"))
1890 }
1891 }
1892 Value::Object(ref v) => {
1893 let len = v.len();
1894 let mut deserializer = MapRefDeserializer::new(v);
1895 let map = try!(visitor.visit_map(&mut deserializer));
1896 let remaining = deserializer.iter.len();
1897 if remaining == 0 {
1898 Ok(map)
1899 } else {
1900 Err(de::Error::invalid_length(len, &"fewer elements in map"))
1901 }
1902 }
1903 }
1904 }
1905
1906 fn deserialize_option<V>(
1907 self,
1908 visitor: V
1909 ) -> Result<V::Value, Error>
1910 where V: de::Visitor,
1911 {
1912 match *self {
1913 Value::Null => visitor.visit_none(),
1914 _ => visitor.visit_some(self),
1915 }
1916 }
1917
1918 fn deserialize_enum<V>(
1919 self,
1920 _name: &str,
1921 _variants: &'static [&'static str],
1922 visitor: V
1923 ) -> Result<V::Value, Error>
1924 where V: de::Visitor,
1925 {
1926 let (variant, value) = match *self {
1927 Value::Object(ref value) => {
1928 let mut iter = value.into_iter();
1929 let (variant, value) = match iter.next() {
1930 Some(v) => v,
1931 None => {
1932 return Err(de::Error::invalid_value(Unexpected::Map, &"map with a single key"));
1933 }
1934 };
1935 // enums are encoded in json as maps with a single key:value pair
1936 if iter.next().is_some() {
1937 return Err(de::Error::invalid_value(Unexpected::Map, &"map with a single key"));
1938 }
1939 (variant, Some(value))
1940 }
1941 Value::String(ref variant) => (variant, None),
1942 ref other => {
1943 return Err(de::Error::invalid_type(other.unexpected(), &"string or map"));
1944 }
1945 };
1946
1947 visitor.visit_enum(EnumRefDeserializer {
1948 variant: variant,
1949 value: value,
1950 })
1951 }
1952
1953 #[inline]
1954 fn deserialize_newtype_struct<V>(
1955 self,
1956 _name: &'static str,
1957 visitor: V
1958 ) -> Result<V::Value, Self::Error>
1959 where V: de::Visitor,
1960 {
1961 visitor.visit_newtype_struct(self)
1962 }
1963
1964 forward_to_deserialize! {
1965 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
1966 seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct
1967 struct_field tuple ignored_any
1968 }
1969 }
1970
1971 struct EnumRefDeserializer<'a> {
1972 variant: &'a str,
1973 value: Option<&'a Value>,
1974 }
1975
1976 impl<'a> de::EnumVisitor for EnumRefDeserializer<'a> {
1977 type Error = Error;
1978 type Variant = VariantRefDeserializer<'a>;
1979
1980 fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Error>
1981 where V: de::DeserializeSeed,
1982 {
1983 let variant = self.variant.into_deserializer();
1984 let visitor = VariantRefDeserializer { value: self.value };
1985 seed.deserialize(variant).map(|v| (v, visitor))
1986 }
1987 }
1988
1989 struct VariantRefDeserializer<'a> {
1990 value: Option<&'a Value>,
1991 }
1992
1993 impl<'a> de::VariantVisitor for VariantRefDeserializer<'a> {
1994 type Error = Error;
1995
1996 fn visit_unit(self) -> Result<(), Error> {
1997 match self.value {
1998 Some(value) => de::Deserialize::deserialize(value),
1999 None => Ok(()),
2000 }
2001 }
2002
2003 fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value, Error>
2004 where T: de::DeserializeSeed,
2005 {
2006 match self.value {
2007 Some(value) => seed.deserialize(value),
2008 None => Err(de::Error::invalid_type(Unexpected::UnitVariant, &"newtype variant")),
2009 }
2010 }
2011
2012 fn visit_tuple<V>(
2013 self,
2014 _len: usize,
2015 visitor: V
2016 ) -> Result<V::Value, Error>
2017 where V: de::Visitor,
2018 {
2019 match self.value {
2020 Some(&Value::Array(ref v)) => {
2021 de::Deserializer::deserialize(SeqRefDeserializer::new(v), visitor)
2022 }
2023 Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"tuple variant")),
2024 None => Err(de::Error::invalid_type(Unexpected::UnitVariant, &"tuple variant"))
2025 }
2026 }
2027
2028 fn visit_struct<V>(
2029 self,
2030 _fields: &'static [&'static str],
2031 visitor: V
2032 ) -> Result<V::Value, Error>
2033 where V: de::Visitor,
2034 {
2035 match self.value {
2036 Some(&Value::Object(ref v)) => {
2037 de::Deserializer::deserialize(MapRefDeserializer::new(v), visitor)
2038 }
2039 Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"struct variant")),
2040 _ => Err(de::Error::invalid_type(Unexpected::UnitVariant, &"struct variant"))
2041 }
2042 }
2043 }
2044
2045 struct SeqRefDeserializer<'a> {
2046 iter: slice::Iter<'a, Value>,
2047 }
2048
2049 impl<'a> SeqRefDeserializer<'a> {
2050 fn new(slice: &'a [Value]) -> Self {
2051 SeqRefDeserializer {
2052 iter: slice.iter(),
2053 }
2054 }
2055 }
2056
2057 impl<'a> de::Deserializer for SeqRefDeserializer<'a> {
2058 type Error = Error;
2059
2060 #[inline]
2061 fn deserialize<V>(mut self, visitor: V) -> Result<V::Value, Error>
2062 where V: de::Visitor,
2063 {
2064 let len = self.iter.len();
2065 if len == 0 {
2066 visitor.visit_unit()
2067 } else {
2068 let ret = try!(visitor.visit_seq(&mut self));
2069 let remaining = self.iter.len();
2070 if remaining == 0 {
2071 Ok(ret)
2072 } else {
2073 Err(de::Error::invalid_length(len, &"fewer elements in array"))
2074 }
2075 }
2076 }
2077
2078 forward_to_deserialize! {
2079 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
2080 seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
2081 tuple_struct struct struct_field tuple enum ignored_any
2082 }
2083 }
2084
2085 impl<'a> de::SeqVisitor for SeqRefDeserializer<'a> {
2086 type Error = Error;
2087
2088 fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
2089 where T: de::DeserializeSeed,
2090 {
2091 match self.iter.next() {
2092 Some(value) => seed.deserialize(value).map(Some),
2093 None => Ok(None),
2094 }
2095 }
2096
2097 fn size_hint(&self) -> (usize, Option<usize>) {
2098 self.iter.size_hint()
2099 }
2100 }
2101
2102 struct MapRefDeserializer<'a> {
2103 iter: <&'a Map<String, Value> as IntoIterator>::IntoIter,
2104 value: Option<&'a Value>,
2105 }
2106
2107 impl<'a> MapRefDeserializer<'a> {
2108 fn new(map: &'a Map<String, Value>) -> Self {
2109 MapRefDeserializer {
2110 iter: map.into_iter(),
2111 value: None,
2112 }
2113 }
2114 }
2115
2116 impl<'a> de::MapVisitor for MapRefDeserializer<'a> {
2117 type Error = Error;
2118
2119 fn visit_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
2120 where T: de::DeserializeSeed,
2121 {
2122 match self.iter.next() {
2123 Some((key, value)) => {
2124 self.value = Some(value);
2125 seed.deserialize((&**key).into_deserializer()).map(Some)
2126 }
2127 None => Ok(None),
2128 }
2129 }
2130
2131 fn visit_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Error>
2132 where T: de::DeserializeSeed,
2133 {
2134 match self.value.take() {
2135 Some(value) => seed.deserialize(value),
2136 None => Err(de::Error::custom("value is missing")),
2137 }
2138 }
2139
2140 fn size_hint(&self) -> (usize, Option<usize>) {
2141 self.iter.size_hint()
2142 }
2143 }
2144
2145 impl<'a> de::Deserializer for MapRefDeserializer<'a> {
2146 type Error = Error;
2147
2148 #[inline]
2149 fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
2150 where V: de::Visitor,
2151 {
2152 visitor.visit_map(self)
2153 }
2154
2155 forward_to_deserialize! {
2156 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
2157 seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
2158 tuple_struct struct struct_field tuple enum ignored_any
2159 }
2160 }
2161
2162 impl Value {
2163 fn unexpected(&self) -> Unexpected {
2164 match *self {
2165 Value::Null => Unexpected::Unit,
2166 Value::Bool(b) => Unexpected::Bool(b),
2167 Value::Number(ref n) => {
2168 if let Some(u) = n.as_u64() {
2169 Unexpected::Unsigned(u)
2170 } else if let Some(i) = n.as_i64() {
2171 Unexpected::Signed(i)
2172 } else if let Some(f) = n.as_f64() {
2173 Unexpected::Float(f)
2174 } else {
2175 panic!("unexpected number")
2176 }
2177 }
2178 Value::String(ref s) => Unexpected::Str(s),
2179 Value::Array(_) => Unexpected::Seq,
2180 Value::Object(_) => Unexpected::Map,
2181 }
2182 }
2183 }
2184
2185 /// Convert a `T` into `serde_json::Value` which is an enum that can represent
2186 /// any valid JSON data.
2187 ///
2188 /// This conversion can fail if `T`'s implementation of `Serialize` decides to
2189 /// fail, or if `T` contains a map with non-string keys.
2190 ///
2191 /// ```rust
2192 /// # use serde_json::Value;
2193 /// let val = serde_json::to_value("s").unwrap();
2194 /// assert_eq!(val, Value::String("s".to_owned()));
2195 /// ```
2196 #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
2197 // Taking by value is more friendly to iterator adapters, option and result
2198 // consumers, etc. See https://github.com/serde-rs/json/pull/149.
2199 pub fn to_value<T>(value: T) -> Result<Value, Error>
2200 where T: ser::Serialize,
2201 {
2202 value.serialize(Serializer)
2203 }
2204
2205 /// Interpret a `serde_json::Value` as an instance of type `T`.
2206 ///
2207 /// This conversion can fail if the structure of the Value does not match the
2208 /// structure expected by `T`, for example if `T` is a struct type but the Value
2209 /// contains something other than a JSON map. It can also fail if the structure
2210 /// is correct but `T`'s implementation of `Deserialize` decides that something
2211 /// is wrong with the data, for example required struct fields are missing from
2212 /// the JSON map or some number is too big to fit in the expected primitive
2213 /// type.
2214 pub fn from_value<T>(value: Value) -> Result<T, Error>
2215 where T: de::Deserialize,
2216 {
2217 de::Deserialize::deserialize(value)
2218 }
2219
2220 /// Representation of any serializable data as a `serde_json::Value`.
2221 pub trait ToJson {
2222 /// Represent `self` as a `serde_json::Value`. Note that `Value` is not a
2223 /// JSON string. If you need a string, use `serde_json::to_string` instead.
2224 ///
2225 /// This conversion can fail if `T`'s implementation of `Serialize` decides
2226 /// to fail, or if `T` contains a map with non-string keys.
2227 fn to_json(&self) -> Result<Value, Error>;
2228 }
2229
2230 impl<T: ?Sized> ToJson for T
2231 where T: ser::Serialize,
2232 {
2233 fn to_json(&self) -> Result<Value, Error> {
2234 to_value(self)
2235 }
2236 }