• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use crate::generator::{format, stringify, JsonGenerateResult, JsonGenerator};
2 use std::collections::HashMap;
3 use std::convert::TryFrom;
4 use std::fmt;
5 use std::io;
6 use std::ops::{Index, IndexMut};
7 
8 const NULL: () = ();
9 
10 /// Enum to represent one JSON value. Each variant represents corresponding JSON types.
11 /// ```
12 /// use tinyjson::JsonValue;
13 /// use std::convert::TryInto;
14 ///
15 /// // Convert from raw values using `From` trait
16 /// let value = JsonValue::from("this is string".to_string());
17 ///
18 /// // Get reference to inner value
19 /// let maybe_number: Option<&f64> = value.get();
20 /// assert!(maybe_number.is_none());
21 /// let maybe_string: Option<&String> = value.get();
22 /// assert!(maybe_string.is_some());
23 ///
24 /// // Check type of JSON value
25 /// assert!(matches!(value, JsonValue::String(_)));
26 /// assert!(value.is_string());
27 ///
28 /// // Convert into raw values using `TryInto` trait
29 /// let original_value: String = value.try_into().unwrap();
30 /// ```
31 #[derive(Debug, Clone, PartialEq)]
32 pub enum JsonValue {
33     /// Number type value.
34     Number(f64),
35     /// Boolean type value.
36     Boolean(bool),
37     /// String type value.
38     String(String),
39     /// Null type value.
40     Null,
41     /// Array type value.
42     Array(Vec<JsonValue>),
43     /// Object type value.
44     Object(HashMap<String, JsonValue>),
45 }
46 
47 /// Trait to access to inner value of `JsonValue` as reference.
48 ///
49 /// This is used by several APIs like [`JsonValue::get`] to represent any inner values of [`JsonValue`].
50 pub trait InnerAsRef {
json_value_as(v: &JsonValue) -> Option<&Self>51     fn json_value_as(v: &JsonValue) -> Option<&Self>;
52 }
53 
54 macro_rules! impl_inner_ref {
55     ($to:ty, $pat:pat => $val:expr) => {
56         impl InnerAsRef for $to {
57             fn json_value_as(v: &JsonValue) -> Option<&$to> {
58                 use JsonValue::*;
59                 match v {
60                     $pat => Some($val),
61                     _ => None,
62                 }
63             }
64         }
65     };
66 }
67 
68 impl_inner_ref!(f64, Number(n) => n);
69 impl_inner_ref!(bool, Boolean(b) => b);
70 impl_inner_ref!(String, String(s) => s);
71 impl_inner_ref!((), Null => &NULL);
72 impl_inner_ref!(Vec<JsonValue>, Array(a) => a);
73 impl_inner_ref!(HashMap<String, JsonValue>, Object(h) => h);
74 
75 /// Trait to access to inner value of `JsonValue` as mutable reference.
76 ///
77 /// This is a mutable version of [`InnerAsRef`].
78 pub trait InnerAsRefMut {
json_value_as_mut(v: &mut JsonValue) -> Option<&mut Self>79     fn json_value_as_mut(v: &mut JsonValue) -> Option<&mut Self>;
80 }
81 
82 macro_rules! impl_inner_ref_mut {
83     ($to:ty, $pat:pat => $val:expr) => {
84         impl InnerAsRefMut for $to {
85             fn json_value_as_mut(v: &mut JsonValue) -> Option<&mut $to> {
86                 use JsonValue::*;
87                 match v {
88                     $pat => Some($val),
89                     _ => None,
90                 }
91             }
92         }
93     };
94 }
95 
96 impl_inner_ref_mut!(f64, Number(n) => n);
97 impl_inner_ref_mut!(bool, Boolean(b) => b);
98 impl_inner_ref_mut!(String, String(s) => s);
99 impl_inner_ref_mut!(Vec<JsonValue>, Array(a) => a);
100 impl_inner_ref_mut!(HashMap<String, JsonValue>, Object(h) => h);
101 
102 // Note: matches! is available from Rust 1.42
103 macro_rules! is_xxx {
104     (
105         $(#[$meta:meta])*
106         $name:ident,
107         $variant:pat,
108     ) => {
109         $(#[$meta])*
110         pub fn $name(&self) -> bool {
111             match self {
112                 $variant => true,
113                 _ => false,
114             }
115         }
116     };
117 }
118 
119 impl JsonValue {
120     /// Get immutable reference to the inner value.
121     ///
122     /// ```
123     /// use tinyjson::JsonValue;
124     ///
125     /// let value: JsonValue = "[1, 2, 3]".parse().unwrap();
126     /// let vec: &Vec<_> = value.get().unwrap();
127     /// assert_eq!(vec[0], JsonValue::from(1.0));
128     ///
129     /// // Try to convert with incorrect type
130     /// assert!(value.get::<f64>().is_none());
131     /// ```
get<T: InnerAsRef>(&self) -> Option<&T>132     pub fn get<T: InnerAsRef>(&self) -> Option<&T> {
133         T::json_value_as(self)
134     }
135 
136     /// Get mutable reference to the inner value.
137     ///
138     /// ```
139     /// use tinyjson::JsonValue;
140     ///
141     /// let mut value: JsonValue = "[1, 2, 3]".parse().unwrap();
142     /// let vec: &mut Vec<_> = value.get_mut().unwrap();
143     /// vec[0] = JsonValue::from(false);
144     /// assert_eq!(value.stringify().unwrap(), "[false,2,3]");
145     ///
146     /// // Try to convert with incorrect type
147     /// assert!(value.get_mut::<f64>().is_none());
148     /// ```
get_mut<T: InnerAsRefMut>(&mut self) -> Option<&mut T>149     pub fn get_mut<T: InnerAsRefMut>(&mut self) -> Option<&mut T> {
150         T::json_value_as_mut(self)
151     }
152 
153     is_xxx!(
154         /// Check if the inner value is a boolean.
155         ///
156         /// ```
157         /// use tinyjson::JsonValue;
158         ///
159         /// let v = JsonValue::from(true);
160         /// assert!(v.is_bool());
161         /// let v = JsonValue::from(1.0);
162         /// assert!(!v.is_bool());
163         /// ```
164         is_bool,
165         JsonValue::Boolean(_),
166     );
167     is_xxx!(
168         /// Check if the inner value is a number.
169         ///
170         /// ```
171         /// use tinyjson::JsonValue;
172         ///
173         /// let v = JsonValue::from(1.0);
174         /// assert!(v.is_number());
175         /// let v = JsonValue::from(false);
176         /// assert!(!v.is_number());
177         /// ```
178         is_number,
179         JsonValue::Number(_),
180     );
181     is_xxx!(
182         /// Check if the inner value is a string.
183         ///
184         /// ```
185         /// use tinyjson::JsonValue;
186         ///
187         /// let v = JsonValue::from("foo".to_string());
188         /// assert!(v.is_string());
189         /// let v = JsonValue::from(1.0);
190         /// assert!(!v.is_string());
191         /// ```
192         is_string,
193         JsonValue::String(_),
194     );
195     is_xxx!(
196         /// Check if the inner value is null.
197         ///
198         /// ```
199         /// use tinyjson::JsonValue;
200         ///
201         /// let v = JsonValue::from(()); // () is inner representation of null value
202         /// assert!(v.is_null());
203         /// let v = JsonValue::from(false);
204         /// assert!(!v.is_null());
205         /// ```
206         is_null,
207         JsonValue::Null,
208     );
209     is_xxx!(
210         /// Check if the inner value is an array.
211         ///
212         /// ```
213         /// use tinyjson::JsonValue;
214         ///
215         /// let v = JsonValue::from(vec![]);
216         /// assert!(v.is_array());
217         /// let v = JsonValue::from(1.0);
218         /// assert!(!v.is_array());
219         /// ```
220         is_array,
221         JsonValue::Array(_),
222     );
223     is_xxx!(
224         /// Check if the inner value is an object.
225         ///
226         /// ```
227         /// use tinyjson::JsonValue;
228         /// use std::collections::HashMap;
229         ///
230         /// let v = JsonValue::from(HashMap::new());
231         /// assert!(v.is_object());
232         /// let v = JsonValue::from(vec![]);
233         /// assert!(!v.is_object());
234         /// ```
235         is_object,
236         JsonValue::Object(_),
237     );
238 
239     /// Convert this JSON value to `String` value.
240     ///
241     /// ```
242     /// use tinyjson::JsonValue;
243     ///
244     /// let v = JsonValue::from(vec![1.0.into(), true.into(), "str".to_string().into()]);
245     /// let s = v.stringify().unwrap();
246     /// assert_eq!(&s, "[1,true,\"str\"]");
247     /// ```
stringify(&self) -> JsonGenerateResult248     pub fn stringify(&self) -> JsonGenerateResult {
249         stringify(self)
250     }
251 
252     /// Write this JSON value to the given `io::Write` object as UTF-8 byte sequence.
253     ///
254     /// ```
255     /// use tinyjson::JsonValue;
256     /// use std::io::Write;
257     ///
258     /// let v = JsonValue::from(vec![1.0.into(), true.into(), "str".to_string().into()]);
259     /// let mut bytes = vec![];
260     /// v.write_to(&mut bytes).unwrap();
261     /// assert_eq!(&String::from_utf8(bytes).unwrap(), "[1,true,\"str\"]");
262     /// ```
write_to<W: io::Write>(&self, w: &mut W) -> io::Result<()>263     pub fn write_to<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
264         JsonGenerator::new(w).generate(self)
265     }
266 
267     /// Convert this JSON value to `String` value with 2-spaces indentation.
268     ///
269     /// ```
270     /// use tinyjson::JsonValue;
271     ///
272     /// let v = JsonValue::from(vec![1.0.into(), true.into(), "str".to_string().into()]);
273     /// let s = v.format().unwrap();
274     /// assert_eq!(&s,
275     /// "[
276     ///   1,
277     ///   true,
278     ///   \"str\"
279     /// ]");
280     /// ```
format(&self) -> JsonGenerateResult281     pub fn format(&self) -> JsonGenerateResult {
282         format(self)
283     }
284 
285     /// Write this JSON value to the given `io::Write` object as UTF-8 byte sequence with 2-spaces indentation.
286     ///
287     /// ```
288     /// use tinyjson::JsonValue;
289     ///
290     /// let v = JsonValue::from(vec![1.0.into(), true.into(), "str".to_string().into()]);
291     /// let mut bytes = vec![];
292     /// v.format_to(&mut bytes).unwrap();
293     /// assert_eq!(&String::from_utf8(bytes).unwrap(),
294     /// "[
295     ///   1,
296     ///   true,
297     ///   \"str\"
298     /// ]");
299     /// ```
format_to<W: io::Write>(&self, w: &mut W) -> io::Result<()>300     pub fn format_to<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
301         JsonGenerator::new(w).indent("  ").generate(self)
302     }
303 }
304 
305 /// Access to value of the key of object.
306 ///
307 /// ```
308 /// use tinyjson::JsonValue;
309 /// use std::collections::HashMap;
310 ///
311 /// let mut m = HashMap::new();
312 /// m.insert("foo".to_string(), 1.0.into());
313 /// let v = JsonValue::from(m);
314 /// let i = &v["foo"];
315 /// assert_eq!(i, &JsonValue::Number(1.0));
316 /// ```
317 ///
318 ///  This will panic when the given `JsonValue` value is not an object
319 ///
320 /// ```should_panic
321 /// # use tinyjson::JsonValue;
322 /// let v = JsonValue::from(vec![]);
323 /// let _ = &v["foo"]; // Panic
324 /// ```
325 ///
326 /// or when the key does not exist in the object.
327 ///
328 /// ```should_panic
329 /// # use tinyjson::JsonValue;
330 /// # use std::collections::HashMap;
331 /// let v = JsonValue::from(HashMap::new());
332 /// let _ = &v["foo"]; // Panic
333 /// ```
334 ///
335 /// Using this operator, you can access the nested elements quickly
336 ///
337 /// ```
338 /// # use tinyjson::JsonValue;
339 /// let mut json: JsonValue = r#"
340 /// {
341 ///   "foo": {
342 ///     "bar": [
343 ///       { "target": 42 }
344 ///     ]
345 ///   }
346 /// }
347 /// "#.parse().unwrap();
348 ///
349 /// // Access with index operator
350 /// let target_value: f64 = *json["foo"]["bar"][0]["target"].get().unwrap();
351 /// assert_eq!(target_value, 42.0);
352 /// ```
353 
354 impl<'a> Index<&'a str> for JsonValue {
355     type Output = JsonValue;
356 
index(&self, key: &'a str) -> &Self::Output357     fn index(&self, key: &'a str) -> &Self::Output {
358         let obj = match self {
359             JsonValue::Object(o) => o,
360             _ => panic!(
361                 "Attempted to access to an object with key '{}' but actually it was {:?}",
362                 key, self
363             ),
364         };
365 
366         match obj.get(key) {
367             Some(json) => json,
368             None => panic!("Key '{}' was not found in {:?}", key, self),
369         }
370     }
371 }
372 
373 /// Access to value of the index of array.
374 ///
375 /// ```
376 /// use tinyjson::JsonValue;
377 ///
378 /// let v = JsonValue::from(vec![1.0.into(), true.into()]);
379 /// let b = &v[1];
380 /// assert_eq!(b, &JsonValue::Boolean(true));
381 /// ```
382 ///
383 ///  This will panic when the given `JsonValue` value is not an array
384 ///
385 /// ```should_panic
386 /// # use tinyjson::JsonValue;
387 /// use std::collections::HashMap;
388 /// let v = JsonValue::from(HashMap::new());
389 /// let _ = &v[0]; // Panic
390 /// ```
391 ///
392 /// or when the index is out of bounds.
393 ///
394 /// ```should_panic
395 /// # use tinyjson::JsonValue;
396 /// let v = JsonValue::from(vec![]);
397 /// let _ = &v[0]; // Panic
398 /// ```
399 impl Index<usize> for JsonValue {
400     type Output = JsonValue;
401 
index(&self, index: usize) -> &'_ Self::Output402     fn index(&self, index: usize) -> &'_ Self::Output {
403         let array = match self {
404             JsonValue::Array(a) => a,
405             _ => panic!(
406                 "Attempted to access to an array with index {} but actually the value was {:?}",
407                 index, self,
408             ),
409         };
410         &array[index]
411     }
412 }
413 
414 /// Access to value of the key of mutable object.
415 ///
416 /// ```
417 /// use tinyjson::JsonValue;
418 /// use std::collections::HashMap;
419 ///
420 /// let mut m = HashMap::new();
421 /// m.insert("foo".to_string(), 1.0.into());
422 /// let mut v = JsonValue::from(m);
423 /// v["foo"] = JsonValue::Number(3.14);
424 /// assert_eq!(v["foo"], JsonValue::Number(3.14));
425 /// ```
426 ///
427 ///  This will panic when the given `JsonValue` value is not an object
428 ///
429 /// ```should_panic
430 /// # use tinyjson::JsonValue;
431 /// let mut v = JsonValue::from(vec![]);
432 /// let _ = &mut v["foo"]; // Panic
433 /// ```
434 ///
435 /// or when the key does not exist in the object.
436 ///
437 /// ```should_panic
438 /// # use tinyjson::JsonValue;
439 /// # use std::collections::HashMap;
440 /// let mut v = JsonValue::from(HashMap::new());
441 /// let _ = &mut v["foo"]; // Panic
442 /// ```
443 ///
444 /// Using this operator, you can modify the nested elements quickly
445 ///
446 /// ```
447 /// # use tinyjson::JsonValue;
448 /// let mut json: JsonValue = r#"
449 /// {
450 ///   "foo": {
451 ///     "bar": [
452 ///       { "target": 42 }
453 ///     ]
454 ///   }
455 /// }
456 /// "#.parse().unwrap();
457 ///
458 /// // Modify with index operator
459 /// json["foo"]["bar"][0]["target"] = JsonValue::Boolean(false);
460 /// assert_eq!(json["foo"]["bar"][0]["target"], JsonValue::Boolean(false));
461 /// ```
462 impl<'a> IndexMut<&'a str> for JsonValue {
index_mut(&mut self, key: &'a str) -> &mut Self::Output463     fn index_mut(&mut self, key: &'a str) -> &mut Self::Output {
464         let obj = match self {
465             JsonValue::Object(o) => o,
466             _ => panic!(
467                 "Attempted to access to an object with key '{}' but actually it was {:?}",
468                 key, self
469             ),
470         };
471 
472         if let Some(json) = obj.get_mut(key) {
473             json
474         } else {
475             panic!("Key '{}' was not found in object", key)
476         }
477     }
478 }
479 
480 /// Access to value of the index of mutable array.
481 ///
482 /// ```
483 /// use tinyjson::JsonValue;
484 ///
485 /// let mut v = JsonValue::from(vec![1.0.into(), true.into()]);
486 /// let b = &mut v[1];
487 /// assert_eq!(b, &JsonValue::Boolean(true));
488 /// ```
489 ///
490 ///  This will panic when the given `JsonValue` value is not an array
491 ///
492 /// ```should_panic
493 /// # use tinyjson::JsonValue;
494 /// use std::collections::HashMap;
495 /// let mut v = JsonValue::from(HashMap::new());
496 /// let _ = &mut v[0]; // Panic
497 /// ```
498 ///
499 /// or when the index is out of bounds.
500 ///
501 /// ```should_panic
502 /// # use tinyjson::JsonValue;
503 /// let mut v = JsonValue::from(vec![]);
504 /// let _ = &mut v[0]; // Panic
505 /// ```
506 impl IndexMut<usize> for JsonValue {
index_mut(&mut self, index: usize) -> &mut Self::Output507     fn index_mut(&mut self, index: usize) -> &mut Self::Output {
508         let array = match self {
509             JsonValue::Array(a) => a,
510             _ => panic!(
511                 "Attempted to access to an array with index {} but actually the value was {:?}",
512                 index, self,
513             ),
514         };
515 
516         &mut array[index]
517     }
518 }
519 
520 macro_rules! impl_from {
521     (
522         $(#[$meta:meta])*
523         $v:ident: $t:ty => $e:expr
524     ) => {
525         $(#[$meta])*
526         impl From<$t> for JsonValue {
527             fn from($v: $t) -> JsonValue {
528                 use JsonValue::*;
529                 $e
530             }
531         }
532     };
533 }
534 
535 impl_from!(
536     /// Convert `f64` value into `JsonValue`.
537     ///
538     /// ```
539     /// use tinyjson::JsonValue;
540     /// let v = JsonValue::from(1.0);
541     /// assert!(v.is_number());
542     /// ```
543     n: f64 => Number(n)
544 );
545 impl_from!(
546     /// Convert `bool` value into `JsonValue`.
547     ///
548     /// ```
549     /// use tinyjson::JsonValue;
550     /// let v = JsonValue::from(true);
551     /// assert!(v.is_bool());
552     /// ```
553     b: bool => Boolean(b)
554 );
555 impl_from!(
556     /// Convert `bool` value into `JsonValue`. Note that `&str` is not available. Explicitly allocate `String` object
557     /// and pass it.
558     ///
559     /// ```
560     /// use tinyjson::JsonValue;
561     /// let v = JsonValue::from("foo".to_string());
562     /// assert!(v.is_string());
563     /// ```
564     s: String => String(s)
565 );
566 impl_from!(
567     /// Convert `()` into `JsonValue`. `()` is an inner representation of null JSON value.
568     ///
569     /// ```
570     /// use tinyjson::JsonValue;
571     /// let v = JsonValue::from(());
572     /// assert!(v.is_null());
573     /// ```
574     _x: () => Null
575 );
576 impl_from!(
577     /// Convert `Vec` value into `JsonValue`.
578     ///
579     /// ```
580     /// use tinyjson::JsonValue;
581     /// let v = JsonValue::from(vec![1.0.into(), true.into()]);
582     /// assert!(v.is_array());
583     /// ```
584     a: Vec<JsonValue> => Array(a)
585 );
586 impl_from!(
587     /// Convert `HashMap` value into `JsonValue`.
588     ///
589     /// ```
590     /// use tinyjson::JsonValue;
591     /// use std::collections::HashMap;
592     /// let mut m = HashMap::new();
593     /// m.insert("foo".to_string(), 1.0.into());
594     /// let v = JsonValue::from(m);
595     /// assert!(v.is_object());
596     /// ```
597     o: HashMap<String, JsonValue> => Object(o)
598 );
599 
600 /// Error caused when trying to convert `JsonValue` into some wrong type value.
601 ///
602 /// ```
603 /// use tinyjson::{JsonValue, UnexpectedValue};
604 /// use std::convert::TryFrom;
605 ///
606 /// let error = String::try_from(JsonValue::from(1.0)).unwrap_err();
607 /// assert!(matches!(error, UnexpectedValue{..}));
608 /// ```
609 #[derive(Debug)]
610 pub struct UnexpectedValue {
611     value: JsonValue,
612     expected: &'static str,
613 }
614 
615 impl UnexpectedValue {
616     /// Get reference to the value which failed to be converted.
617     ///
618     /// ```
619     /// use tinyjson::JsonValue;
620     /// use std::convert::TryFrom;
621     ///
622     /// let error = String::try_from(JsonValue::from(1.0)).unwrap_err();
623     /// assert_eq!(error.value(), &JsonValue::Number(1.0));
624     /// ```
value(&self) -> &JsonValue625     pub fn value(&self) -> &JsonValue {
626         &self.value
627     }
628 }
629 
630 impl fmt::Display for UnexpectedValue {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result631     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
632         write!(
633             f,
634             "Unexpected JSON value: {:?}. Expected {} value",
635             self.value, self.expected
636         )
637     }
638 }
639 
640 impl std::error::Error for UnexpectedValue {}
641 
642 /// Convert this error into the value which failed to be converted.
643 ///
644 /// ```
645 /// use tinyjson::JsonValue;
646 /// use std::convert::TryFrom;
647 ///
648 /// let error = String::try_from(JsonValue::from(1.0)).unwrap_err();
649 /// assert_eq!(JsonValue::from(error), JsonValue::Number(1.0));
650 /// ```
651 impl From<UnexpectedValue> for JsonValue {
from(err: UnexpectedValue) -> Self652     fn from(err: UnexpectedValue) -> Self {
653         err.value
654     }
655 }
656 
657 macro_rules! impl_try_from {
658     (
659         $(#[$meta:meta])*
660         $pat:pat => $val:expr,
661         $ty:ty,
662     ) => {
663         $(#[$meta])*
664         impl TryFrom<JsonValue> for $ty {
665             type Error = UnexpectedValue;
666 
667             fn try_from(v: JsonValue) -> Result<Self, UnexpectedValue> {
668                 match v {
669                     $pat => Ok($val),
670                     v => Err(UnexpectedValue {
671                         value: v,
672                         expected: stringify!($ty),
673                     }),
674                 }
675             }
676         }
677     };
678 }
679 
680 impl_try_from!(
681     /// Try to convert the `JsonValue` value into `f64`. `UnexpectedValue` error happens when trying to convert an
682     /// incorrect type value.
683     ///
684     /// ```
685     /// use tinyjson::JsonValue;
686     /// use std::convert::TryFrom;
687     ///
688     /// let v = JsonValue::from(1.0);
689     /// let r = f64::try_from(v);
690     /// assert!(r.is_ok());
691     ///
692     /// let v = JsonValue::from(true);
693     /// let r = f64::try_from(v);
694     /// assert!(r.is_err());
695     /// ```
696     JsonValue::Number(n) => n,
697     f64,
698 );
699 impl_try_from!(
700     /// Try to convert the `JsonValue` value into `bool`. `UnexpectedValue` error happens when trying to convert an
701     /// incorrect type value.
702     ///
703     /// ```
704     /// use tinyjson::JsonValue;
705     /// use std::convert::TryFrom;
706     ///
707     /// let v = JsonValue::from(true);
708     /// let r = bool::try_from(v);
709     /// assert!(r.is_ok());
710     ///
711     /// let v = JsonValue::from(1.0);
712     /// let r = bool::try_from(v);
713     /// assert!(r.is_err());
714     /// ```
715     JsonValue::Boolean(b) => b,
716     bool,
717 );
718 impl_try_from!(
719     /// Try to convert the `JsonValue` value into `String`. `UnexpectedValue` error happens when trying to convert an
720     /// incorrect type value.
721     ///
722     /// ```
723     /// use tinyjson::JsonValue;
724     /// use std::convert::TryFrom;
725     ///
726     /// let v = JsonValue::from("foo".to_string());
727     /// let r = String::try_from(v);
728     /// assert!(r.is_ok());
729     ///
730     /// let v = JsonValue::from(1.0);
731     /// let r = String::try_from(v);
732     /// assert!(r.is_err());
733     /// ```
734     JsonValue::String(s) => s,
735     String,
736 );
737 impl_try_from!(
738     /// Try to convert the `JsonValue` value into `()`. Note that `()` is an inner representation of null JSON value.
739     /// `UnexpectedValue` error happens when trying to convert an incorrect type value.
740     ///
741     /// ```
742     /// use tinyjson::JsonValue;
743     /// use std::convert::TryFrom;
744     ///
745     /// let v = JsonValue::from(());
746     /// let r = <()>::try_from(v);
747     /// assert!(r.is_ok());
748     ///
749     /// let v = JsonValue::from(1.0);
750     /// let r = <()>::try_from(v);
751     /// assert!(r.is_err());
752     /// ```
753     JsonValue::Null => (),
754     (),
755 );
756 impl_try_from!(
757     /// Try to convert the `JsonValue` value into `Vec<JsonValue>`. `UnexpectedValue` error happens when trying to
758     /// convert an incorrect type value.
759     ///
760     /// ```
761     /// use tinyjson::JsonValue;
762     /// use std::convert::TryFrom;
763     ///
764     /// let v = JsonValue::from(vec![true.into()]);
765     /// let r = <Vec<_>>::try_from(v);
766     /// assert!(r.is_ok());
767     ///
768     /// let v = JsonValue::from(1.0);
769     /// let r = <Vec<_>>::try_from(v);
770     /// assert!(r.is_err());
771     /// ```
772     JsonValue::Array(a) => a,
773     Vec<JsonValue>,
774 );
775 impl_try_from!(
776     /// Try to convert the `JsonValue` value into `HashMap<String, JsonValue>`. `UnexpectedValue` error happens when
777     /// trying to convert an incorrect type value.
778     ///
779     /// ```
780     /// use tinyjson::JsonValue;
781     /// use std::convert::TryFrom;
782     /// use std::collections::HashMap;
783     ///
784     /// let mut m = HashMap::new();
785     /// m.insert("foo".to_string(), 42.0.into());
786     /// let v = JsonValue::from(m);
787     /// let r = <HashMap<_, _>>::try_from(v);
788     /// assert!(r.is_ok());
789     ///
790     /// let v = JsonValue::from(1.0);
791     /// let r = <HashMap<_, _>>::try_from(v);
792     /// assert!(r.is_err());
793     /// ```
794     JsonValue::Object(o) => o,
795     HashMap<String, JsonValue>,
796 );
797