json_commons/commons/
json.rs

1use std::collections::vec_deque::VecDeque;
2use json::{JsonValue, parse};
3use std::fs::File;
4use std::io::Read;
5use bson::{Array, Bson, Document};
6
7pub struct JsonCommons {}
8
9
10impl JsonCommons {
11
12    /// Creates a new instance of `JsonCommons`
13    /// # Example
14    /// ```rust
15    /// use json_commons::JsonCommons;
16    ///
17    /// let jsonc = JsonCommons::new();
18    /// ```
19    pub fn new() -> JsonCommons {
20        return JsonCommons {};
21    }
22
23    /// Read a `&str` and parse to a `JsonValue`.
24    /// # Panics
25    /// Panics if content cannot be parsed to a `JsonValue`.
26    /// # Example
27    /// ```rust
28    /// let content = "{\"car\": {\"model\": \"Gurgel Itaipu E400\", \"color\": \"red\"}}";
29    ///
30    /// let json = jsonc.read_str(content);
31    /// ```
32    pub fn read_str(&self, content: &str) -> JsonValue {
33        return parse(content).expect("Failed to parse content to JSON");
34    }
35
36    /// Open and parse all file content to a `JsonValue`
37    /// # Panics
38    /// - If occurs an error to open or read file
39    /// - If content cannot be parsed to a `JsonValue`
40    /// # Example
41    /// ```rust
42    /// let path = "/user/docs/myfile.json";
43    /// let json = jsonc.read_file(path);
44    /// ```
45    pub fn read_file(&self, file_path: &str) -> JsonValue {
46        let mut file = File::open(file_path).expect(format!("Failed to open {}", file_path).as_str());
47        let mut content = String::new();
48        file.read_to_string(&mut content).expect(format!("Failed to read content from {}", file_path).as_str());
49        return self.read_str(content.as_str())
50    }
51
52    /// You can get any dotted path as an Optional
53    ///
54    /// If path is not found then return is `None`
55    pub fn get_path(&self, path: &str, content: JsonValue) -> Option<JsonValue> {
56        let mut keys = path.split(".")
57            .map(|key| key.to_string())
58            .collect::<VecDeque<String>>();
59
60        if keys.is_empty() {
61            return None;
62        }
63
64        let key = keys.pop_front().unwrap();
65
66        if content.has_key(&key) && keys.len() > 0 {
67            return if content[&key].is_array() {
68                let parse_index = keys.pop_front().unwrap().parse::<usize>();
69
70                match parse_index {
71                    Ok(index) => {
72                        let array = self.parse_to_vec(content[&key].to_owned());
73
74                        match array.get(index).cloned() {
75                            Some(object) => {
76                                let last_key = format!("{}.{}", &key, &index);
77                                return if keys.len() > 0 {
78                                    self.get_path(&self.gen_path(path.to_string(), last_key), object)
79                                } else {
80                                    return Some(object)
81                                }
82                            }
83                            None => None
84                        }
85                    },
86                    Err(_) => None
87                }
88            } else {
89                self.get_path(&self.gen_path(path.to_string(), key.to_owned()), content[&key].to_owned())
90            }
91        }
92
93        return if content.has_key(&key) {
94            Some(content.to_owned()[&key].take())
95        } else {
96            None
97        };
98    }
99
100    /// Check if a dotted path exists
101    pub fn path_exists(&self, path: &str, content: JsonValue) -> bool {
102        return self.get_path(&path, content.to_owned()).is_some();
103    }
104
105    /// Parse a list of `JsonValue` to a `VecDeque<JsonValue>`
106    ///
107    /// # Examples
108    ///
109    /// Consider the following content
110    ///
111    /// ```json
112    /// {
113    ///   "cars": [
114    ///     {
115    ///      "model": "Gurgel Itaipu E400",
116    ///       "color": "red"
117    ///     },
118    ///     {
119    ///       "model": "Gurgel X15",
120    ///       "color": "brown"
121    ///     }
122    ///   ]
123    /// }
124    /// ```
125    ///
126    /// You can Parse the key **__cars__** to a vec
127    ///
128    /// ```rust
129    /// let json = jsonc.read_str(content);
130    /// let cars = jsonc.get_path("cars", json).unwrap();
131    ///
132    /// jsonc.parse_to_vec(cars); // The output is a vec of JsonValue, with len 2
133    /// ```
134    pub fn parse_to_vec(&self, content: JsonValue) -> VecDeque<JsonValue> {
135        let mut vec = VecDeque::<JsonValue>::new();
136        if content.is_array() && content.members().len() > 0 {
137            for member in content.members() {
138                vec.push_back(member.to_owned());
139            }
140        }
141        return vec;
142    }
143
144    /// Serialize a `JsonValue` into a `String`.
145    ///
146    /// Consider the following content
147    /// ```json
148    /// {
149    ///     "car": {
150    ///         "model": "Gurgel Itaipu E4000",
151    ///         "color": "red"
152    ///     }
153    /// }
154    /// ```
155    /// Output is equivalent to Javascript **__JSON.stringify__**
156    /// ```rust
157    /// let serialized = jsonc.serialize(myjson);
158    /// assert_eq!("{\"car\":{\"model\":\"Gurgel Itaipu E400\",\"color\":\"red\"}}", serialized);
159    /// ```
160    pub fn serialize(&self, json: JsonValue) -> String {
161        return format!("{:#}", format!("{}", json.to_string()));
162    }
163
164    /// Parse a `Document` into a `JsonValue`
165    pub fn json_from_document(&self, doc: Document) -> JsonValue {
166        return self.read_str(format!("{:#}", format!("{}", doc.to_string())).as_str())
167    }
168
169    /// Parse a `Bson` into a `JsonValue`
170    pub fn json_from_bson(&self, bson: Bson) -> JsonValue {
171        return self.read_str(format!("{:#}", format!("{}", bson.to_string())).as_str())
172    }
173
174    /// Parse a Hex String into a `JsonValue`
175    pub fn json_from_bson_hex(&self, bson_hex: String) -> JsonValue {
176        let bytes = hex::decode(bson_hex).expect("Failed to decode hex");
177        let doc = Document::from_reader(&mut bytes.as_slice()).expect("Failed to read bytes");
178        return self.json_from_document(doc);
179    }
180
181    /// Parse a `JsonValue` into a  `Document`
182    pub fn parse_to_document(&self, json: JsonValue) -> Document {
183        let mut document = Document::new();
184
185        for (key, value) in json.entries() {
186            document.insert(key, self.bson_value(value.to_owned()));
187        }
188
189        return document
190    }
191
192    /// Parse a `JsonValue` into a `Bson`
193    pub fn parse_to_bson(&self, json: JsonValue) -> Bson {
194        return Bson::from(self.parse_to_document(json.to_owned()))
195    }
196
197    /// Serialize a `JsonValue` into a Hex `String`.
198    ///
199    /// Consider the following content
200    /// ```json
201    /// {
202    ///     "car": {
203    ///         "model": "Gurgel Itaipu E4000",
204    ///         "color": "red"
205    ///     }
206    /// }
207    /// ```
208    /// Output is a encoded Hex BSON
209    /// ```rust
210    /// let bson_hex = jsonc.serialize_to_bson_hex(myjson);
211    /// assert_eq!("3c000000036361720032000000026d6f64656c001300000047757267656c2049746169707520453430300002636f6c6f720004000000726564000000", bson_hex);
212    /// ```
213    pub fn serialize_to_bson_hex(&self, json: JsonValue) -> String {
214        let document = self.parse_to_document(json.to_owned());
215        let mut bytes: Vec<u8> = vec![];
216        document.to_writer(&mut bytes).expect("Failed to write bytes");
217        return hex::encode(bytes.as_slice());
218    }
219
220    // Private Functions
221    fn gen_path(&self, path: String, last_key: String) -> String {
222        return path.replace(format!("{}.", last_key).as_str(), "");
223    }
224
225    fn bson_value(&self, value: JsonValue) -> Bson {
226
227        if value.is_null() {
228            return Bson::Null
229        }
230
231        if value.is_string() {
232            return Bson::from(value.to_owned().as_str().unwrap());
233        }
234
235        if value.is_boolean() {
236            return Bson::from(value.to_owned().as_bool().unwrap());
237        }
238
239        if value.is_number() {
240            let number = value.to_owned().take().as_number().unwrap().to_string();
241            let float = number.parse::<f64>();
242
243            match float {
244                Ok(float_value) => {
245                    return if float_value.fract() != 0.0 {
246                        Bson::from(float_value)
247                    } else {
248                        Bson::from(float_value as i64)
249                    }
250                },
251                Err(e) => panic!("{}", e)
252            }
253        }
254
255        if value.is_object() {
256            return Bson::from(self.parse_to_document(value.to_owned()));
257        }
258
259        if value.is_array() {
260            let mut array = Array::new();
261
262            for entry in self.parse_to_vec(value.to_owned()) {
263                array.push(self.bson_value(entry.to_owned()));
264            }
265
266            return Bson::from(array);
267        }
268
269        return Bson::Null;
270    }
271}