1use serde_json;
2use std::fmt::{Debug, Display, Formatter};
3use std::io;
4use std::num::{ParseFloatError, ParseIntError};
5use std::path::Path;
6use std::pin::Pin;
7use std::slice::{Iter, IterMut};
8use std::string::FromUtf8Error;
9use std::task::{Context, Poll};
10use std::vec::IntoIter;
11use serde::{Deserialize, Serialize};
12use serde_json::{to_string_pretty, Error};
13use object::Object;
14use crate::number::Number;
15use crate::object::{ObjectIntoIter, ObjectIter, ObjectIterMut};
16
17mod object;
18mod json_impl;
19pub mod number;
20pub mod ext;
21
22pub struct JsonError {
23 msg: String,
24}
25
26impl Debug for JsonError {
27 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
28 f.write_str(&self.msg)
29 }
30}
31
32impl Display for JsonError {
33 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
34 f.write_str(&self.msg)
35 }
36}
37
38unsafe impl Send for JsonError {}
39
40impl Future for JsonError {
41 type Output = String;
42
43 fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
44 let poll = Poll::from(self.msg.clone());
45 poll
46 }
47}
48
49impl From<&str> for JsonError {
50 fn from(msg: &str) -> Self {
51 JsonError { msg: msg.to_string() }
52 }
53}
54
55impl From<ParseFloatError> for JsonError {
56 fn from(err: ParseFloatError) -> Self {
57 JsonError { msg: err.to_string() }
58 }
59}
60
61impl From<io::Error> for JsonError {
62 fn from(value: io::Error) -> Self {
63 JsonError { msg: value.to_string() }
64 }
65}
66
67impl From<FromUtf8Error> for JsonError {
68 fn from(value: FromUtf8Error) -> Self {
69 JsonError { msg: value.to_string() }
70 }
71}
72
73impl From<ParseIntError> for JsonError {
74 fn from(value: ParseIntError) -> Self {
75 JsonError { msg: value.to_string() }
76 }
77}
78
79impl From<Error> for JsonError {
80 fn from(value: Error) -> Self {
81 JsonError { msg: value.to_string() }
82 }
83}
84
85impl std::error::Error for JsonError {}
86
87
88type JsonResult<T> = Result<T, JsonError>;
89
90static NULL: JsonValue = JsonValue::Null;
91
92pub fn parse(source: impl AsRef<str>) -> JsonResult<JsonValue> {
93 Ok(serde_json::from_str(source.as_ref())?)
94}
95
96pub fn from_file(fp: impl AsRef<Path>) -> JsonResult<JsonValue> {
97 let b = std::fs::read(fp.as_ref())?;
98 let s = String::from_utf8(b)?;
99 parse(s.as_str())
100}
101
102pub fn from_bytes(context: impl AsRef<[u8]>) -> JsonResult<JsonValue> {
103 let s = String::from_utf8(context.as_ref().to_vec())?;
104 parse(s.as_str())
105}
106
107pub fn to_string<T: Serialize>(t: &T) -> JsonResult<String> {
108 Ok(serde_json::to_string(t)?)
109}
110
111pub fn from_struct<T: Serialize>(t: &T) -> JsonResult<JsonValue> {
112 let s = to_string(t)?;
113 parse(s.as_str())
114}
115
116
117#[derive(Clone)]
118pub enum JsonValue {
119 Null,
120 String(String),
121 Number(Number),
122 Boolean(bool),
123 Object(Object),
124 Array(Vec<JsonValue>),
125}
126
127impl Display for JsonValue {
128 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
129 if f.alternate() {
130 f.write_str(&self.pretty())
131 } else {
132 f.write_str(self.dump().as_str())
133 }
134 }
135}
136
137impl JsonValue {
138 pub fn new_object() -> JsonValue {
139 JsonValue::Object(Object::new())
140 }
141
142 pub fn new_array() -> JsonValue {
143 JsonValue::Array(vec![])
144 }
145
146 pub fn push<T>(&mut self, value: T)
147 where
148 T: Into<JsonValue>,
149 {
150 match self {
151 JsonValue::Array(vec) => vec.push(value.into()),
152 _ => {}
153 }
154 }
155
156 pub fn len(&self) -> usize {
157 match *self {
158 JsonValue::Array(ref vec) => vec.len(),
159 JsonValue::Object(ref object) => object.len(),
160 _ => 0
161 }
162 }
163
164 pub fn insert<T>(&mut self, key: &str, value: T) -> JsonResult<()>
165 where
166 T: Into<JsonValue>,
167 {
168 match self {
169 JsonValue::Object(o) => { Ok(o.insert(key, value.into())) }
170 _ => Err("Wrong Type Object!".into())
171 }
172 }
173
174 pub fn pretty(&self) -> String {
175 match self {
176 JsonValue::Null => "null".to_string(),
177 JsonValue::String(v) => v.clone(),
178 _ => to_string_pretty(self).unwrap()
179 }
180 }
181
182 pub fn dump(&self) -> String {
183 match self {
184 JsonValue::Null => "null".to_string(),
185 JsonValue::String(v) => v.clone(),
186 _ => to_string(self).unwrap()
187 }
188 }
189
190 pub fn has_key(&self, key: &str) -> bool {
191 match *self {
192 JsonValue::Object(ref object) => !object.get(key).is_null(),
193 _ => false
194 }
195 }
196
197 pub fn members(&self) -> Iter<'_, JsonValue> {
198 match self {
199 JsonValue::Array(vec) => vec.iter(),
200 _ => [].iter()
201 }
202 }
203
204 pub fn members_mut(&mut self) -> IterMut<'_, JsonValue> {
205 match self {
206 JsonValue::Array(vec) => vec.iter_mut(),
207 _ => [].iter_mut()
208 }
209 }
210
211 pub fn into_members(self) -> IntoIter<JsonValue> {
212 match self {
213 JsonValue::Array(vec) => vec.into_iter(),
214 _ => vec![].into_iter()
215 }
216 }
217
218 pub fn entries(&self) -> ObjectIter<'_> {
219 match self {
220 JsonValue::Object(object) => object.iter(),
221 _ => ObjectIter::empty()
222 }
223 }
224
225 pub fn entries_mut(&mut self) -> ObjectIterMut<'_> {
226 match self {
227 JsonValue::Object(object) => object.iter_mut(),
228 _ => ObjectIterMut::empty()
229 }
230 }
231
232 pub fn into_entries(self) -> ObjectIntoIter {
233 match self {
234 JsonValue::Object(object) => object.into_iter(),
235 _ => ObjectIntoIter::empty()
236 }
237 }
238
239 pub fn clear(&mut self) {
240 match self {
241 JsonValue::String(string) => string.clear(),
242 JsonValue::Object(object) => object.clear(),
243 JsonValue::Array(vec) => vec.clear(),
244 _ => *self = JsonValue::Null,
245 }
246 }
247
248 pub fn remove(&mut self, key: &str) -> JsonValue {
249 match self {
250 JsonValue::Object(object) => object.remove(key),
251 _ => JsonValue::Null,
252 }
253 }
254
255 pub fn array_remove(&mut self, index: usize) -> JsonValue {
256 match self {
257 JsonValue::Array(array) => { array.remove(index) }
258 _ => JsonValue::Null
259 }
260 }
261
262 pub fn as_struct<T: for<'a> Deserialize<'a>>(&self) -> JsonResult<T> {
264 let s = self.dump();
265 Ok(serde_json::from_str(s.as_str())?)
266 }
267
268 pub fn write_file(&self, fp: impl AsRef<Path>) -> JsonResult<()> {
269 std::fs::write(fp.as_ref(), self.pretty())?;
270 Ok(())
271 }
272
273 fn update(json1: &mut JsonValue, json2: JsonValue) -> JsonResult<()> {
274 for (k, v) in json2.entries() {
275 if v.is_object() && json1.has_key(k) {
276 if json1[k].is_null() {
277 json1[k] = JsonValue::new_object();
278 }
279 if !json1[k].is_object() {
280 json1[k] = JsonValue::new_object();
281 }
282 Self::update(&mut json1[k], json2[k].clone())?;
283 continue;
284 } else if v.is_object() && !json1.has_key(k) {
285 if json1[k].is_null() {
286 json1[k] = JsonValue::new_array()
287 }
288 if !json1[k].is_array() {
289 json1[k] = JsonValue::new_array();
290 }
291 json1.insert(k, json2[k].clone())?;
292 continue;
293 }
294 json1.insert(k, json2[k].clone())?;
295 }
296 Ok(())
297 }
298
299 pub fn update_by(&mut self, other: JsonValue) -> JsonResult<()> {
300 Self::update(self, other)
301 }
302
303 fn set_by_xpath(&mut self, xp: &[String], value: JsonValue) -> JsonResult<()> {
304 if xp.len() != 0 {
305 if xp[0].starts_with("[") && xp[0].ends_with("]") {
306 if !self.is_array() { return Err("xpath error-current is not array".into()); }
307 let index = xp[0].replace("[", "").replace("]", "").parse::<usize>()?;
308 self[index].set_by_xpath(&xp[1..], value)?;
309 } else {
310 if !self.is_object() { return Err("xpath error-current is not object".into()); }
311 self[xp[0].as_str()].set_by_xpath(&xp[1..], value)?;
312 };
313 } else {
314 *self = value;
315 }
316 Ok(())
317 }
318
319 pub fn set_value_by_xpath<T: Into<JsonValue>>(&mut self, xpath: &str, other: T) -> JsonResult<()> {
320 let paths = xpath.split('.').collect::<Vec<_>>();
321 let xpaths = paths.iter().filter_map(|x| if x != &"" { Some(x.to_string()) } else { None }).collect::<Vec<_>>();
322 self.set_by_xpath(xpaths.as_slice(), other.into())?;
323 Ok(())
324 }
325
326 fn get_by_xpath(&self, xp: &[String]) -> JsonResult<&JsonValue> {
327 if xp.len() != 0 {
328 if xp[0].starts_with("[") && xp[0].ends_with("]") {
329 if !self.is_array() { return Err("xpath error-current is not array".into()); }
330 let index = xp[0].replace("[", "").replace("]", "").parse::<usize>()?;
331 self[index].get_by_xpath(&xp[1..])
332 } else {
333 if !self.is_object() { return Err("xpath error-current is not object".into()); }
334 self[xp[0].as_str()].get_by_xpath(&xp[1..])
335 }
336 } else {
337 Ok(self)
338 }
339 }
340
341 pub fn xpath(&self, xpath: &str) -> JsonResult<&JsonValue> {
342 let paths = xpath.split('.').collect::<Vec<_>>();
343 let xpaths = paths.iter().filter_map(|x| if x != &"" { Some(x.to_string()) } else { None }).collect::<Vec<_>>();
344 self.get_by_xpath(xpaths.as_slice())
345 }
346
347 fn remove_by_xpath(&mut self, xp: &[String]) -> JsonResult<JsonValue> {
348 if xp.len() == 1 {
349 if xp[0].starts_with("[") && xp[0].ends_with("]") {
350 if !self.is_array() { return Err("xpath error-current is not array".into()); }
351 let index = xp[0].replace("[", "").replace("]", "").parse::<usize>()?;
352 Ok(self.array_remove(index))
353 } else {
354 if !self.is_object() { return Err("xpath error-current is not object".into()); }
355 Ok(self.remove(xp[0].as_str()))
356 }
357 } else {
358 if xp[0].starts_with("[") && xp[0].ends_with("]") {
359 if !self.is_array() { return Err("xpath error-current is not array".into()); }
360 let index = xp[0].replace("[", "").replace("]", "").parse::<usize>()?;
361 self[index].remove_by_xpath(&xp[1..])
362 } else {
363 if !self.is_object() { return Err("xpath error-current is not object".into()); }
364 self[xp[0].as_str()].remove_by_xpath(&xp[1..])
365 }
366 }
367 }
368
369 pub fn remove_value_by_xpath(&mut self, xpath: &str) -> JsonResult<JsonValue> {
370 let paths = xpath.split('.').collect::<Vec<_>>();
371 let xpaths = paths.iter().filter_map(|x| if x != &"" { Some(x.to_string()) } else { None }).collect::<Vec<_>>();
372 if xpaths.len() == 0 { return Err("xpath error".into()); }
373 self.remove_by_xpath(xpaths.as_slice())
374 }
375
376 pub fn into_key(mut self, key: impl AsRef<str>) -> JsonValue {
377 self.remove(key.as_ref())
378 }
379
380 pub fn into_index(mut self, index: usize) -> JsonValue {
381 self.array_remove(index)
382 }
383}
384
385impl Debug for JsonValue {
386 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
387 f.write_str(self.dump().as_str())
388 }
389}
390
391unsafe impl Send for JsonValue {}
392
393
394#[macro_export]
401macro_rules! array {
402 [] => ($crate::JsonValue::new_array());
403
404 [@ITEM($( $i:expr, )*) $item:tt, $( $cont:tt )+] => {
406 $crate::array!(
407 @ITEM($( $i, )* $crate::value!($item), )
408 $( $cont )*
409 )
410 };
411 (@ITEM($( $i:expr, )*) $item:tt,) => ({
412 $crate::array!(@END $( $i, )* $crate::value!($item), )
413 });
414 (@ITEM($( $i:expr, )*) $item:tt) => ({
415 $crate::array!(@END $( $i, )* $crate::value!($item), )
416 });
417
418 [@ITEM($( $i:expr, )*) $item:expr, $( $cont:tt )+] => {
420 $crate::array!(
421 @ITEM($( $i, )* $crate::value!($item), )
422 $( $cont )*
423 )
424 };
425 (@ITEM($( $i:expr, )*) $item:expr,) => ({
426 $crate::array!(@END $( $i, )* $crate::value!($item), )
427 });
428 (@ITEM($( $i:expr, )*) $item:expr) => ({
429 $crate::array!(@END $( $i, )* $crate::value!($item), )
430 });
431
432 (@END $( $i:expr, )*) => ({
434 let size = 0 $( + {let _ = &$i; 1} )*;
435 let mut array = Vec::with_capacity(size);
436
437 $(
438 array.push($i.into());
439 )*
440
441 $crate::JsonValue::Array(array)
442 });
443
444 ($( $cont:tt )+) => {
446 $crate::array!(@ITEM() $($cont)*)
447 };
448}
449
450#[macro_export]
451macro_rules! value {
454 ( null ) => { $crate::JsonValue::Null };
455 ( [$( $token:tt )*] ) => {
456 $crate::array![ $( $token )* ]
458 };
459 ( {$( $token:tt )*} ) => {
460 $crate::object!{ $( $token )* }
461 };
462 { $value:expr } => { $value };
463}
464
465#[macro_export]
477macro_rules! object {
478 {} => ($crate::JsonValue::new_object());
480
481 (@ENTRY($( $k:expr => $v:expr, )*) $key:ident: $( $cont:tt )*) => {
483 $crate::object!(@ENTRY($( $k => $v, )*) stringify!($key) => $($cont)*)
484 };
485 (@ENTRY($( $k:expr => $v:expr, )*) $key:literal: $( $cont:tt )*) => {
486 $crate::object!(@ENTRY($( $k => $v, )*) $key => $($cont)*)
487 };
488 (@ENTRY($( $k:expr => $v:expr, )*) [$key:expr]: $( $cont:tt )*) => {
489 $crate::object!(@ENTRY($( $k => $v, )*) $key => $($cont)*)
490 };
491
492 (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:tt, $( $cont:tt )+) => {
494 $crate::object!(
495 @ENTRY($( $k => $v, )* $key => $crate::value!($value), )
496 $( $cont )*
497 )
498 };
499 (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:tt,) => ({
500 $crate::object!(@END $( $k => $v, )* $key => $crate::value!($value), )
501 });
502 (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:tt) => ({
503 $crate::object!(@END $( $k => $v, )* $key => $crate::value!($value), )
504 });
505
506 (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:expr, $( $cont:tt )+) => {
508 $crate::object!(
509 @ENTRY($( $k => $v, )* $key => $crate::value!($value), )
510 $( $cont )*
511 )
512 };
513 (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:expr,) => ({
514 $crate::object!(@END $( $k => $v, )* $key => $crate::value!($value), )
515 });
516
517 (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:expr) => ({
518 $crate::object!(@END $( $k => $v, )* $key => $crate::value!($value), )
519 });
520
521 (@END $( $k:expr => $v:expr, )*) => ({
523 let mut object = $crate::JsonValue::new_object();
525
526
527 $(
528 let s=$crate::JsonValue::from($v);
529 object.insert($k, s).unwrap();
530 )*
531 object
532 });
534
535 ($key:tt: $( $cont:tt )+) => {
537 $crate::object!(@ENTRY() $key: $($cont)*)
538 };
539
540 ($( $k:expr => $v:expr, )*) => {
542 $crate::object!(@END $( $k => $crate::value!($v), )*)
543 };
544 ($( $k:expr => $v:expr ),*) => {
545 $crate::object!(@END $( $k => $crate::value!($v), )*)
546 };
547}
548
549
550
551
552