1mod macros;
2mod parser;
3mod serialize;
4mod traits;
5
6pub use parser::json_parse;
7pub use traits::FromJson;
8pub use traits::ToJson;
9
10use std::ops;
11
12#[derive(Debug, PartialEq, Clone)]
13pub enum JsonElem {
14
15 Null,
22
23 Bool(bool),
30
31 Number(f64),
38
39 Str(String),
46
47 Array(Vec<JsonElem>),
54
55 Object(std::collections::HashMap<String, JsonElem>),
62}
63
64impl JsonElem {
65
66 pub fn get<T: FromJson>(self) -> Option<T> {
74 T::from_json(self)
75 }
76
77 pub fn is_null(&self) -> bool {
78 matches!(self, JsonElem::Null)
79 }
80
81 pub fn is_bool(&self) -> bool {
82 matches!(self, JsonElem::Bool(_))
83 }
84
85 pub fn is_string(&self) -> bool {
86 matches!(self, JsonElem::Str(_))
87 }
88
89 pub fn is_array(&self) -> bool {
90 matches!(self, JsonElem::Array(_))
91 }
92
93 pub fn is_object(&self) -> bool {
94 matches!(self, JsonElem::Object(_))
95 }
96}
97
98impl ops::Index<usize> for JsonElem {
99 type Output = JsonElem;
100 fn index(&self, idx: usize) -> &Self::Output {
101 match self {
102 JsonElem::Array(a) if idx < a.len() => &a[idx],
103 _ => &JsonElem::Null,
104 }
105 }
106}
107
108impl ops::Index<&str> for JsonElem {
109 type Output = JsonElem;
110 fn index(&self, idx: &str) -> &Self::Output {
111 match self {
112 JsonElem::Object(o) if o.contains_key(idx) => &o[idx],
113 _ => &JsonElem::Null,
114 }
115 }
116}
117
118#[derive(Debug, PartialEq, Eq, Clone)]
119pub enum JsonParseErr {
120 ExpectValue,
121 InvalidValue,
122 RootNotSingular,
123 InvalidStringEscape,
124 MissQuotationMark,
125 InvalidStringChar,
126 InvalidUnicodeHex,
127 InvalidUnicodeSurrogate,
128 ArrayMissCommaOrSquareBacket,
129 ObjectMissCommaOrCurlyBacket,
130 ObjectMissKey,
131 ObjectMissColon,
132}