json_commons/commons/
json.rs1use 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 pub fn new() -> JsonCommons {
20 return JsonCommons {};
21 }
22
23 pub fn read_str(&self, content: &str) -> JsonValue {
33 return parse(content).expect("Failed to parse content to JSON");
34 }
35
36 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 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 pub fn path_exists(&self, path: &str, content: JsonValue) -> bool {
102 return self.get_path(&path, content.to_owned()).is_some();
103 }
104
105 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 pub fn serialize(&self, json: JsonValue) -> String {
161 return format!("{:#}", format!("{}", json.to_string()));
162 }
163
164 pub fn json_from_document(&self, doc: Document) -> JsonValue {
166 return self.read_str(format!("{:#}", format!("{}", doc.to_string())).as_str())
167 }
168
169 pub fn json_from_bson(&self, bson: Bson) -> JsonValue {
171 return self.read_str(format!("{:#}", format!("{}", bson.to_string())).as_str())
172 }
173
174 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 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 pub fn parse_to_bson(&self, json: JsonValue) -> Bson {
194 return Bson::from(self.parse_to_document(json.to_owned()))
195 }
196
197 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 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}