arson/
json.rs

1use super::{parser::Parser, JSONError};
2use std::collections::HashMap;
3use std::fmt;
4use std::str::FromStr;
5use termion::color;
6
7/// Contains the JSON types and can be used to parse strings to json
8#[derive(PartialEq)]
9pub enum JSON {
10    /// JSON Object
11    Object(HashMap<String, JSON>),
12    /// JSON Array
13    Array(Vec<JSON>),
14    /// JSON String
15    String(String),
16    /// JSON Number
17    Number(f64),
18    /// JSON Boolean
19    Bool(bool),
20    /// JSON Null
21    Null,
22}
23
24impl FromStr for JSON {
25    type Err = JSONError;
26
27    fn from_str(json: &str) -> Result<JSON, JSONError> {
28        Ok(Parser::parse(json.chars())?)
29    }
30}
31
32impl fmt::Debug for JSON {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match self {
35            JSON::Array(x) => write!(f, "{:#?}", x),
36            JSON::Number(x) => write!(
37                f,
38                "{}{}{}",
39                color::Fg(color::Blue),
40                x,
41                color::Fg(color::Reset)
42            ),
43            JSON::String(x) => write!(
44                f,
45                r#"{}"{}"{}"#,
46                color::Fg(color::LightGreen),
47                x,
48                color::Fg(color::Reset),
49            ),
50            JSON::Bool(x) => write!(
51                f,
52                "{}{}{}",
53                color::Fg(color::Magenta),
54                x,
55                color::Fg(color::Reset),
56            ),
57            JSON::Null => write!(
58                f,
59                "{}null{}",
60                color::Fg(color::Green),
61                color::Fg(color::Reset),
62            ),
63            JSON::Object(x) => {
64                write!(f, "{:#?}", x)
65            }
66        }
67    }
68}