yan_json 0.2.1

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

impl JsonNode {
    pub fn parse(s: &str) -> Option<Self> {
        let s = s.trim();
        let surrounded = |a, b| s.starts_with(a) && s.ends_with(b);
        Some(match s {
            s if surrounded('{', '}') => Self::Object(
                Self::parse_object(s)?
                    .into_iter()
                    .map(|[k, v]| Self::parse(&v).map(|v| (k, v)))
                    .collect::<Option<HashMap<String, JsonNode>>>()?,
            ),
            s if surrounded('[', ']') => JsonNode::Array(
                Self::parse_array(s)?
                    .iter()
                    .map(|s| Self::parse(s))
                    .collect::<Option<Vec<Self>>>()?,
            ),
            s if surrounded('"', '"') => {
                let s: &str = &s[1..s.len() - 1];
                Self::String(s.to_string())
            }
            s if s.parse::<f64>().is_ok() => JsonNode::Number(s.parse().unwrap()),
            "false" => Self::Bool(false),
            "true" => Self::Bool(true),
            "null" => Self::Null,

            _ => return None,
        })
    }

    fn parse_token_with_stack<I>(it: &mut Peekable<I>) -> (String, Option<char>)
    where
        I: Iterator<Item = char>,
    {
        let mut result = String::new();
        let mut stack: Vec<char> = Vec::new();
        let mut next_to_be_escaped = false;

        loop {
            let Some(c) = it.peek() else {
                break;
            };
            if next_to_be_escaped {
                result.push(*c);
                it.next();
                next_to_be_escaped = false;
                continue;
            }
            if Self::is_bracket(*c) {
                if stack.last() == Some(&'"') {
                    if *c == '"' {
                        stack.pop();
                    }
                    result.push(*c);
                    it.next();
                    continue;
                }
                Self::update_bracket_stack(&mut stack, *c);
                if stack.is_empty() {
                    result.push(*c);
                    it.next();
                    break;
                }
            }
            if c.is_whitespace() && stack.is_empty() {
                if result.is_empty() {
                    it.next();
                    continue;
                }
                break;
            }
            match c {
                '\\' => next_to_be_escaped = true,
                ',' | ':' if stack.is_empty() => break,
                _ => result.push(*c),
            }
            it.next();
        }
        while let Some(c) = it.peek() {
            if c.is_whitespace() {
                it.next();
            } else {
                break;
            }
        }
        (result, it.next().filter(|sep| ![']', '}'].contains(sep)))
    }

    fn parse_object(mut s: &str) -> Option<Vec<[String; 2]>> {
        assert_eq!(s.chars().next(), Some('{'));
        assert_eq!(s.chars().last(), Some('}'));
        s = &s[1..s.len() - 1];

        let mut result: Vec<[String; 2]> = Vec::new();

        let mut it = s.chars().peekable();
        loop {
            if it.peek().is_none() {
                break;
            }
            // reading the key
            let (key, sep) = Self::parse_token_with_stack(&mut it);
            if sep != Some(':') {
                return None;
            }

            let key = if key.chars().next()? == '"' && key.chars().last()? == '"' {
                key[1..key.len() - 1].to_string()
            } else {
                return None;
            };

            let (val, sep) = Self::parse_token_with_stack(&mut it);

            result.push([key, val]);

            match sep {
                None => break,
                Some(',') => {}
                Some(_) => return None,
            }
        }
        if it.next().is_some() {
            None
        } else {
            Some(result)
        }
    }

    fn parse_array(mut s: &str) -> Option<Vec<String>> {
        assert_eq!(s.chars().next(), Some('['));
        assert_eq!(s.chars().last(), Some(']'));
        s = &s[1..s.len() - 1];

        let mut result: Vec<String> = Vec::new();

        let mut it = s.chars().peekable();
        loop {
            let (val, sep) = Self::parse_token_with_stack(&mut it);

            if !val.is_empty() {
                result.push(val);
            }

            match sep {
                None => break,
                Some(',') => {}
                Some(_) => return None,
            }
        }
        Some(result)
    }
    fn is_bracket(c: char) -> bool {
        ['"', '[', ']', '{', '}'].contains(&c)
    }
    fn brackets_match(a: char, b: char) -> bool {
        a == '[' && b == ']' || a == '{' && b == '}'
    }
    fn update_bracket_stack(stack: &mut Vec<char>, c: char) {
        const OPENING: &[char] = &['[', '{'];
        const CLOSING: &[char] = &[']', '}'];

        let top = stack.last();
        match (top, c) {
            (None, '"') => stack.push('"'),
            (None, c) if CLOSING.contains(&c) => panic!(),
            (_, c) if OPENING.contains(&c) => stack.push(c),

            (Some('"'), '"') => {
                stack.pop();
            }
            (Some(top), c) if Self::brackets_match(*top, c) => {
                stack.pop();
            }
            (Some(_), '"') => stack.push('"'),

            _ => panic!("{top:?}, {c}"),
        }
    }
}