yan_json 0.2.5

A lightweight library for easily handling JSON
Documentation
use crate::prelude::*;

/// this struct represents a json node use to manipulate json.
/// Because it implements Display, you can serialize it by calling `to_string()`
#[derive(Debug, Clone, PartialEq)]
pub enum JsonNode {
    Object(HashMap<String, Self>),
    Array(Vec<Self>),
    String(String),
    Number(f64),
    Bool(bool),
    Null,
}

impl JsonNode {
    pub fn as_obj(&self) -> Option<&HashMap<String, Self>> {
        match self {
            Self::Object(fields) => Some(fields),
            _ => None,
        }
    }
    pub fn as_arr(&self) -> Option<&Vec<Self>> {
        match self {
            Self::Array(elements) => Some(elements),
            _ => None,
        }
    }
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::String(s) => Some(s),
            _ => None,
        }
    }
    pub fn as_f64(&self) -> Option<f64> {
        match self {
            Self::Number(x) => Some(*x),
            _ => None,
        }
    }
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Self::Bool(b) => Some(*b),
            _ => None,
        }
    }
    pub fn is_null(&self) -> bool {
        matches!(self, Self::Null)
    }
}

impl From<&str> for JsonNode {
    /// does not parse the string, only creates a JsonNode::String
    fn from(value: &str) -> Self {
        JsonNode::String(value.to_string())
    }
}

impl From<f64> for JsonNode {
    fn from(value: f64) -> Self {
        JsonNode::Number(value)
    }
}

impl From<i32> for JsonNode {
    fn from(value: i32) -> Self {
        JsonNode::Number(value as f64)
    }
}

impl From<bool> for JsonNode {
    fn from(value: bool) -> Self {
        JsonNode::Bool(value)
    }
}