yan_json 0.1.0

A lightweight library for easily handling JSON
Documentation
use std::collections::HashMap;

#[cfg(test)]
mod tests;

/// a convenience macro for creating JsonNodes without boilerplate
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
/// use yan_json::{json, JsonNode};
///
/// let is_req_successful: bool = true;
/// let res_json_macro: JsonNode = json!({
///     "successful": is_req_successful,
///     "result": ["a", "result", "in", "some", "format"],
///     "time took in ms": 300
/// });
/// let res_json_manual: JsonNode = JsonNode::Object(HashMap::from([
///     ("successful".to_string(), is_req_successful.into()),
///     ("result".to_string(), JsonNode::Array(vec!["a".into(), "result".into(), "in".into(), "some".into(), "format".into()])),
///     ("time took in ms".to_string(), 300.0.into())
/// ]));
/// assert_eq!(res_json_macro, res_json_manual);
/// ```
#[macro_export]
macro_rules! json {
    (null) => {
        JsonNode::Null
    };

    ({ $($key:literal : $val:tt),* }) => {
        JsonNode::Object(HashMap::from([$(($key.to_string(), json!($val))),*]))
    };

    ([ $($e:tt),* ]) => {
        JsonNode::Array(vec![$(json!($e)),*])
    };

    ($v:expr) => {
        JsonNode::from($v)
    };
}

#[derive(Debug, PartialEq)]
pub enum JsonNode {
    Object(HashMap<String, Self>),
    Array(Vec<Self>),
    String(String),
    Number(f64),
    Bool(bool),
    Null,
}

impl From<&str> for JsonNode {
    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)
    }
}