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 to_string_pretty(self).unwrap()
176 }
177
178 pub fn dump(&self) -> String {
179 to_string(self).unwrap()
180 }
181
182 pub fn has_key(&self, key: &str) -> bool {
183 match *self {
184 JsonValue::Object(ref object) => !object.get(key).is_null(),
185 _ => false
186 }
187 }
188
189 pub fn members(&self) -> Iter<'_, JsonValue> {
190 match self {
191 JsonValue::Array(vec) => vec.iter(),
192 _ => [].iter()
193 }
194 }
195
196 pub fn members_mut(&mut self) -> IterMut<'_, JsonValue> {
197 match self {
198 JsonValue::Array(vec) => vec.iter_mut(),
199 _ => [].iter_mut()
200 }
201 }
202
203 pub fn into_members(self) -> IntoIter<JsonValue> {
204 match self {
205 JsonValue::Array(vec) => vec.into_iter(),
206 _ => vec![].into_iter()
207 }
208 }
209
210 pub fn entries(&self) -> ObjectIter<'_> {
211 match self {
212 JsonValue::Object(object) => object.iter(),
213 _ => ObjectIter::empty()
214 }
215 }
216
217 pub fn entries_mut(&mut self) -> ObjectIterMut<'_> {
218 match self {
219 JsonValue::Object(object) => object.iter_mut(),
220 _ => ObjectIterMut::empty()
221 }
222 }
223
224 pub fn into_entries(self) -> ObjectIntoIter {
225 match self {
226 JsonValue::Object(object) => object.into_iter(),
227 _ => ObjectIntoIter::empty()
228 }
229 }
230
231 pub fn clear(&mut self) {
232 match self {
233 JsonValue::String(string) => string.clear(),
234 JsonValue::Object(object) => object.clear(),
235 JsonValue::Array(vec) => vec.clear(),
236 _ => *self = JsonValue::Null,
237 }
238 }
239
240 pub fn remove(&mut self, key: &str) -> JsonValue {
241 match self {
242 JsonValue::Object(object) => object.remove(key),
243 _ => JsonValue::Null,
244 }
245 }
246
247 pub fn array_remove(&mut self, index: usize) -> JsonValue {
248 match self {
249 JsonValue::Array(array) => { array.remove(index) }
250 _ => JsonValue::Null
251 }
252 }
253
254 pub fn as_struct<T: for<'a> Deserialize<'a>>(&self) -> JsonResult<T> {
256 let s = self.dump();
257 Ok(serde_json::from_str(s.as_str())?)
258 }
259
260 pub fn write_file(&self, fp: impl AsRef<Path>) -> JsonResult<()> {
261 std::fs::write(fp.as_ref(), self.pretty())?;
262 Ok(())
263 }
264
265 fn update(json1: &mut JsonValue, json2: JsonValue) -> JsonResult<()> {
266 for (k, v) in json2.entries() {
267 if v.is_object() && json1.has_key(k) {
268 if json1[k].is_null() {
269 json1[k] = JsonValue::new_object();
270 }
271 if !json1[k].is_object() {
272 json1[k] = JsonValue::new_object();
273 }
274 Self::update(&mut json1[k], json2[k].clone())?;
275 continue;
276 } else if v.is_object() && !json1.has_key(k) {
277 if json1[k].is_null() {
278 json1[k] = JsonValue::new_array()
279 }
280 if !json1[k].is_array() {
281 json1[k] = JsonValue::new_array();
282 }
283 json1.insert(k, json2[k].clone())?;
284 continue;
285 }
286 json1.insert(k, json2[k].clone())?;
287 }
288 Ok(())
289 }
290
291 pub fn update_by(&mut self, other: JsonValue) -> JsonResult<()> {
292 Self::update(self, other)
293 }
294
295 fn set_by_xpath(&mut self, xp: &[String], value: JsonValue) -> JsonResult<()> {
296 if xp.len() != 0 {
297 if xp[0].starts_with("[") && xp[0].ends_with("]") {
298 if !self.is_array() { return Err("xpath error-current is not array".into()); }
299 let index = xp[0].replace("[", "").replace("]", "").parse::<usize>()?;
300 self[index].set_by_xpath(&xp[1..], value)?;
301 } else {
302 if !self.is_object() { return Err("xpath error-current is not object".into()); }
303 self[xp[0].as_str()].set_by_xpath(&xp[1..], value)?;
304 };
305 } else {
306 *self = value;
307 }
308 Ok(())
309 }
310
311 pub fn set_value_by_xpath<T: Into<JsonValue>>(&mut self, xpath: &str, other: T) -> JsonResult<()> {
312 let paths = xpath.split('.').collect::<Vec<_>>();
313 let xpaths = paths.iter().filter_map(|x| if x != &"" { Some(x.to_string()) } else { None }).collect::<Vec<_>>();
314 self.set_by_xpath(xpaths.as_slice(), other.into())?;
315 Ok(())
316 }
317
318 fn get_by_xpath(&self, xp: &[String]) -> JsonResult<&JsonValue> {
319 if xp.len() != 0 {
320 if xp[0].starts_with("[") && xp[0].ends_with("]") {
321 if !self.is_array() { return Err("xpath error-current is not array".into()); }
322 let index = xp[0].replace("[", "").replace("]", "").parse::<usize>()?;
323 self[index].get_by_xpath(&xp[1..])
324 } else {
325 if !self.is_object() { return Err("xpath error-current is not object".into()); }
326 self[xp[0].as_str()].get_by_xpath(&xp[1..])
327 }
328 } else {
329 Ok(self)
330 }
331 }
332
333 pub fn xpath(&self, xpath: &str) -> JsonResult<&JsonValue> {
334 let paths = xpath.split('.').collect::<Vec<_>>();
335 let xpaths = paths.iter().filter_map(|x| if x != &"" { Some(x.to_string()) } else { None }).collect::<Vec<_>>();
336 self.get_by_xpath(xpaths.as_slice())
337 }
338
339 fn remove_by_xpath(&mut self, xp: &[String]) -> JsonResult<JsonValue> {
340 if xp.len() == 1 {
341 if xp[0].starts_with("[") && xp[0].ends_with("]") {
342 if !self.is_array() { return Err("xpath error-current is not array".into()); }
343 let index = xp[0].replace("[", "").replace("]", "").parse::<usize>()?;
344 Ok(self.array_remove(index))
345 } else {
346 if !self.is_object() { return Err("xpath error-current is not object".into()); }
347 Ok(self.remove(xp[0].as_str()))
348 }
349 } else {
350 if xp[0].starts_with("[") && xp[0].ends_with("]") {
351 if !self.is_array() { return Err("xpath error-current is not array".into()); }
352 let index = xp[0].replace("[", "").replace("]", "").parse::<usize>()?;
353 self[index].remove_by_xpath(&xp[1..])
354 } else {
355 if !self.is_object() { return Err("xpath error-current is not object".into()); }
356 self[xp[0].as_str()].remove_by_xpath(&xp[1..])
357 }
358 }
359 }
360
361 pub fn remove_value_by_xpath(&mut self, xpath: &str) -> JsonResult<JsonValue> {
362 let paths = xpath.split('.').collect::<Vec<_>>();
363 let xpaths = paths.iter().filter_map(|x| if x != &"" { Some(x.to_string()) } else { None }).collect::<Vec<_>>();
364 if xpaths.len() == 0 { return Err("xpath error".into()); }
365 self.remove_by_xpath(xpaths.as_slice())
366 }
367
368 pub fn into_key(mut self, key: impl AsRef<str>) -> JsonValue {
369 self.remove(key.as_ref())
370 }
371
372 pub fn into_index(mut self, index: usize) -> JsonValue {
373 self.array_remove(index)
374 }
375}
376
377impl Debug for JsonValue {
378 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
379 f.write_str(self.dump().as_str())
380 }
381}
382
383unsafe impl Send for JsonValue {}
384
385
386#[macro_export]
393macro_rules! array {
394 [] => ($crate::JsonValue::new_array());
395
396 [@ITEM($( $i:expr, )*) $item:tt, $( $cont:tt )+] => {
398 $crate::array!(
399 @ITEM($( $i, )* $crate::value!($item), )
400 $( $cont )*
401 )
402 };
403 (@ITEM($( $i:expr, )*) $item:tt,) => ({
404 $crate::array!(@END $( $i, )* $crate::value!($item), )
405 });
406 (@ITEM($( $i:expr, )*) $item:tt) => ({
407 $crate::array!(@END $( $i, )* $crate::value!($item), )
408 });
409
410 [@ITEM($( $i:expr, )*) $item:expr, $( $cont:tt )+] => {
412 $crate::array!(
413 @ITEM($( $i, )* $crate::value!($item), )
414 $( $cont )*
415 )
416 };
417 (@ITEM($( $i:expr, )*) $item:expr,) => ({
418 $crate::array!(@END $( $i, )* $crate::value!($item), )
419 });
420 (@ITEM($( $i:expr, )*) $item:expr) => ({
421 $crate::array!(@END $( $i, )* $crate::value!($item), )
422 });
423
424 (@END $( $i:expr, )*) => ({
426 let size = 0 $( + {let _ = &$i; 1} )*;
427 let mut array = Vec::with_capacity(size);
428
429 $(
430 array.push($i.into());
431 )*
432
433 $crate::JsonValue::Array(array)
434 });
435
436 ($( $cont:tt )+) => {
438 $crate::array!(@ITEM() $($cont)*)
439 };
440}
441
442#[macro_export]
443macro_rules! value {
446 ( null ) => { $crate::JsonValue::Null };
447 ( [$( $token:tt )*] ) => {
448 $crate::array![ $( $token )* ]
450 };
451 ( {$( $token:tt )*} ) => {
452 $crate::object!{ $( $token )* }
453 };
454 { $value:expr } => { $value };
455}
456
457#[macro_export]
469macro_rules! object {
470 {} => ($crate::JsonValue::new_object());
472
473 (@ENTRY($( $k:expr => $v:expr, )*) $key:ident: $( $cont:tt )*) => {
475 $crate::object!(@ENTRY($( $k => $v, )*) stringify!($key) => $($cont)*)
476 };
477 (@ENTRY($( $k:expr => $v:expr, )*) $key:literal: $( $cont:tt )*) => {
478 $crate::object!(@ENTRY($( $k => $v, )*) $key => $($cont)*)
479 };
480 (@ENTRY($( $k:expr => $v:expr, )*) [$key:expr]: $( $cont:tt )*) => {
481 $crate::object!(@ENTRY($( $k => $v, )*) $key => $($cont)*)
482 };
483
484 (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:tt, $( $cont:tt )+) => {
486 $crate::object!(
487 @ENTRY($( $k => $v, )* $key => $crate::value!($value), )
488 $( $cont )*
489 )
490 };
491 (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:tt,) => ({
492 $crate::object!(@END $( $k => $v, )* $key => $crate::value!($value), )
493 });
494 (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:tt) => ({
495 $crate::object!(@END $( $k => $v, )* $key => $crate::value!($value), )
496 });
497
498 (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:expr, $( $cont:tt )+) => {
500 $crate::object!(
501 @ENTRY($( $k => $v, )* $key => $crate::value!($value), )
502 $( $cont )*
503 )
504 };
505 (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:expr,) => ({
506 $crate::object!(@END $( $k => $v, )* $key => $crate::value!($value), )
507 });
508
509 (@ENTRY($( $k:expr => $v:expr, )*) $key:expr => $value:expr) => ({
510 $crate::object!(@END $( $k => $v, )* $key => $crate::value!($value), )
511 });
512
513 (@END $( $k:expr => $v:expr, )*) => ({
515 let mut object = $crate::JsonValue::new_object();
517
518
519 $(
520 let s=$crate::JsonValue::from($v);
521 object.insert($k, s).unwrap();
522 )*
523 object
524 });
526
527 ($key:tt: $( $cont:tt )+) => {
529 $crate::object!(@ENTRY() $key: $($cont)*)
530 };
531
532 ($( $k:expr => $v:expr, )*) => {
534 $crate::object!(@END $( $k => $crate::value!($v), )*)
535 };
536 ($( $k:expr => $v:expr ),*) => {
537 $crate::object!(@END $( $k => $crate::value!($v), )*)
538 };
539}
540
541
542
543
544