Skip to content

JSON Schema Validator — Rust source

Validate a JSON document against a draft-07 subset schema: types, required, bounds, patterns, enums, arrays and strict objects, every issue reported at its exact path. Pairs with the schema generator. Runs locally with a shareable link.

This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.

// json-schema-validator — draft-07 SUBSET JSON Schema validator. Rust port
// (canonical TS: src/lib/json-schema-validator.ts; Go twin:
// cli/json-schema-validator). Validates a JSON instance against a schema
// supporting: type (string or array, "integer" counts as "number"), enum,
// const, minimum/maximum/exclusiveMinimum/exclusiveMaximum, minLength/
// maxLength (TS .length counts UTF-16 code units: astral chars are 2),
// pattern, minItems/maxItems, uniqueItems, items, required, properties,
// additionalProperties: false, and the boolean schemas true/false.
// Unsupported keywords ($ref/$defs, oneOf/anyOf/allOf/not, patternProperties,
// dependencies, format, propertyNames, contains) are ignored, exactly like
// the TS lib and the Go twin. Rust's standard library ships neither a JSON
// parser nor a regex engine, so this file carries a terse recursive-descent
// JSON parser (Vec/insertion-ordered tuple maps keep issue ordering aligned
// with the TS Object.keys walk) and a small backtracking regex subset
// (literals, ., ^, $, classes, \d\w\s shorthands, \b, groups, |, * + ?
// {m,n} — greedy; no lookaround/backreferences/non-greedy distinctions,
// which a boolean .test() cannot observe). Numbers print into messages with
// JS Number-to-string rules via js_num (70000, 1.5e-7, 1e+21). Never panics
// — errors travel in the result struct.
#![forbid(unsafe_code)]

// ---- JSON tree -----------------------------------------------------------------

#[derive(Debug, Clone, PartialEq)]
pub enum JVal {
    Nul,
    Bool(bool),
    Num(f64),
    Str(String),
    Arr(Vec<JVal>),
    Obj(Vec<(String, JVal)>), // insertion order preserved
}

#[derive(Debug)]
pub struct Issue {
    pub path: String,
    pub message: String,
}

#[derive(Debug, Default)]
pub struct Result {
    pub valid: bool,
    pub issues: Vec<Issue>,
    pub error: Option<String>, // None when the verdict is real (TS: error: null)
}

// ---- JSON parser (recursive descent) --------------------------------------------

struct P<'a> {
    b: &'a [u8],
    i: usize,
}

impl<'a> P<'a> {
    fn ws(&mut self) {
        while self.i < self.b.len() && matches!(self.b[self.i], b' ' | b'\t' | b'\n' | b'\r') {
            self.i += 1;
        }
    }

    fn peek(&mut self) -> Option<u8> {
        self.ws();
        self.b.get(self.i).copied()
    }

    fn eat(&mut self, c: u8) -> bool {
        if self.peek() == Some(c) {
            self.i += 1;
            true
        } else {
            false
        }
    }

    fn lit(&mut self, word: &str) -> bool {
        if self.b[self.i..].starts_with(word.as_bytes()) {
            self.i += word.len();
            true
        } else {
            false
        }
    }

    fn string(&mut self) -> Option<String> {
        if !self.eat(b'"') {
            return None;
        }
        let mut out: Vec<u8> = Vec::new();
        loop {
            let c = *self.b.get(self.i)?;
            if c == b'"' {
                self.i += 1;
                return Some(String::from_utf8(out).ok()?);
            }
            if c == b'\\' {
                self.i += 1;
                let e = *self.b.get(self.i)?;
                self.i += 1;
                match e {
                    b'"' => out.push(b'"'),
                    b'\\' => out.push(b'\\'),
                    b'/' => out.push(b'/'),
                    b'b' => out.push(8),
                    b'f' => out.push(12),
                    b'n' => out.push(10),
                    b'r' => out.push(13),
                    b't' => out.push(9),
                    b'u' => {
                        let mut cp = self.hex4()?;
                        if (0xD800..=0xDBFF).contains(&cp)
                            && self.b.get(self.i) == Some(&b'\\')
                            && self.b.get(self.i + 1) == Some(&b'u')
                        {
                            let save = self.i;
                            self.i += 2;
                            match self.hex4() {
                                Some(lo) if (0xDC00..=0xDFFF).contains(&lo) => {
                                    cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
                                }
                                _ => {
                                    self.i = save;
                                    cp = 0xFFFD;
                                }
                            }
                        } else if (0xD800..=0xDFFF).contains(&cp) {
                            cp = 0xFFFD;
                        }
                        let mut buf = [0u8; 4];
                        out.extend_from_slice(char::from_u32(cp)?.encode_utf8(&mut buf).as_bytes());
                    }
                    _ => return None,
                }
            } else if c < 0x20 {
                return None;
            } else {
                out.push(c);
                self.i += 1;
            }
        }
    }

    fn hex4(&mut self) -> Option<u32> {
        let mut v: u32 = 0;
        for _ in 0..4 {
            let c = *self.b.get(self.i)?;
            let d = match c {
                b'0'..=b'9' => u32::from(c - b'0'),
                b'a'..=b'f' => u32::from(c - b'a') + 10,
                b'A'..=b'F' => u32::from(c - b'A') + 10,
                _ => return None,
            };
            v = v << 4 | d;
            self.i += 1;
        }
        Some(v)
    }

    fn value(&mut self) -> Option<JVal> {
        match self.peek()? {
            b'n' => self.lit("null").then_some(JVal::Nul),
            b't' => self.lit("true").then_some(JVal::Bool(true)),
            b'f' => self.lit("false").then_some(JVal::Bool(false)),
            b'"' => self.string().map(JVal::Str),
            b'[' => {
                self.i += 1;
                let mut arr = Vec::new();
                if self.eat(b']') {
                    return Some(JVal::Arr(arr));
                }
                loop {
                    arr.push(self.value()?);
                    if self.eat(b',') {
                        continue;
                    }
                    return self.eat(b']').then_some(JVal::Arr(arr));
                }
            }
            b'{' => {
                self.i += 1;
                let mut obj: Vec<(String, JVal)> = Vec::new();
                if self.eat(b'}') {
                    return Some(JVal::Obj(obj));
                }
                loop {
                    self.ws();
                    let key = self.string()?;
                    if !self.eat(b':') {
                        return None;
                    }
                    let val = self.value()?;
                    obj.push((key, val));
                    if self.eat(b',') {
                        continue;
                    }
                    return self.eat(b'}').then_some(JVal::Obj(obj));
                }
            }
            _ => self.number().map(JVal::Num),
        }
    }

    fn number(&mut self) -> Option<f64> {
        let start = self.i;
        if self.peek()? == b'-' || self.peek()? == b'+' {
            self.i += 1;
        }
        if !self.b.get(self.i)?.is_ascii_digit() {
            return None;
        }
        while self.b.get(self.i).map_or(false, |c| c.is_ascii_digit()) {
            self.i += 1;
        }
        if self.b.get(self.i) == Some(&b'.') {
            self.i += 1;
            if !self.b.get(self.i)?.is_ascii_digit() {
                return None;
            }
            while self.b.get(self.i).map_or(false, |c| c.is_ascii_digit()) {
                self.i += 1;
            }
        }
        if matches!(self.b.get(self.i), Some(b'e') | Some(b'E')) {
            self.i += 1;
            if matches!(self.b.get(self.i), Some(b'-') | Some(b'+')) {
                self.i += 1;
            }
            if !self.b.get(self.i)?.is_ascii_digit() {
                return None;
            }
            while self.b.get(self.i).map_or(false, |c| c.is_ascii_digit()) {
                self.i += 1;
            }
        }
        std::str::from_utf8(&self.b[start..self.i]).ok()?.parse().ok()
    }
}

// ---- JS-flavoured helpers ---------------------------------------------------------

// Number.isInteger: finite and equal to its floor.
fn is_integral(v: f64) -> bool {
    v == v.trunc() && v.is_finite()
}

fn kind_of(v: &JVal) -> &'static str {
    match v {
        JVal::Nul => "null",
        JVal::Bool(_) => "boolean",
        JVal::Num(n) => {
            if is_integral(*n) {
                "integer"
            } else {
                "number"
            }
        }
        JVal::Str(_) => "string",
        JVal::Arr(_) => "array",
        JVal::Obj(_) => "object",
    }
}

fn deep_equal(a: &JVal, b: &JVal) -> bool {
    if kind_of(a) != kind_of(b) {
        return false;
    }
    match (a, b) {
        (JVal::Nul, JVal::Nul) => true,
        (JVal::Bool(x), JVal::Bool(y)) => x == y,
        (JVal::Num(x), JVal::Num(y)) => x == y,
        (JVal::Str(x), JVal::Str(y)) => x == y,
        (JVal::Arr(x), JVal::Arr(y)) => {
            x.len() == y.len() && x.iter().zip(y).all(|(u, v)| deep_equal(u, v))
        }
        (JVal::Obj(x), JVal::Obj(y)) => {
            x.len() == y.len()
                && x.iter().all(|(k, v)| {
                    y.iter().any(|(k2, v2)| k2 == k && deep_equal(v, v2))
                })
        }
        _ => false,
    }
}

// JS Number-to-string: plain integers below 1e21, exponential only past the
// JS thresholds (decimal exponent < -6 or >= 21), minimal exponent digits.
fn js_num(v: f64) -> String {
    if v == 0.0 {
        return "0".to_string(); // covers -0
    }
    let neg = v < 0.0;
    let a = if neg { -v } else { v };
    if is_integral(a) && a < 1e21 {
        return format!("{}{}", if neg { "-" } else { "" }, a as i128);
    }
    // Rust's shortest {:e} form ("1.5e-7"), re-rendered to JS thresholds.
    let s = format!("{:e}", a);
    let (mant, eexp) = match s.split_once('e') {
        Some((m, e)) => (m, e.parse::<i64>().unwrap_or(0)),
        None => (s.as_str(), 0),
    };
    let (intpart, frac) = match mant.split_once('.') {
        Some((i, f)) => (i, f),
        None => (mant, ""),
    };
    let mut digits = format!("{intpart}{frac}");
    let mut exp = intpart.len() as i64 - 1 + eexp;
    while digits.len() > 1 && digits.starts_with('0') {
        digits = digits[1..].to_string();
        exp -= 1;
    }
    let sign = if neg { "-" } else { "" };
    if exp < -6 || exp >= 21 {
        let rest = if digits.len() > 1 { format!(".{}", &digits[1..]) } else { String::new() };
        let esign = if exp >= 0 { "+" } else { "-" };
        return format!("{sign}{}{rest}e{esign}{}", &digits[..1], exp.abs());
    }
    if exp < 0 {
        return format!("{sign}0.{}{}", "0".repeat((-exp - 1) as usize), digits);
    }
    if digits.len() as i64 > exp + 1 {
        let cut = (exp + 1) as usize;
        return format!("{sign}{}.{}", &digits[..cut], &digits[cut..]);
    }
    format!("{sign}{}{}", digits, "0".repeat((exp + 1) as usize - digits.len()))
}

// TS .length: UTF-16 code units — astral chars count as 2.
fn utf16_len(s: &str) -> usize {
    s.chars().map(|c| usize::from(c as u32 > 0xFFFF)).sum()
}

// JS String(v) for schema type entries and required keys.
fn js_str(v: &JVal) -> String {
    match v {
        JVal::Nul => "null".to_string(),
        JVal::Bool(b) => if *b { "true" } else { "false" }.to_string(),
        JVal::Num(n) => js_num(*n),
        JVal::Str(s) => s.clone(),
        JVal::Arr(a) => a.iter().map(js_str).collect::<Vec<_>>().join(","),
        JVal::Obj(_) => "[object Object]".to_string(),
    }
}

// ---- regex subset ------------------------------------------------------------------
//
// A small backtracking matcher covering the constructs a draft-07 "pattern"
// realistically uses: literals, '.', '^', '$', character classes with ranges
// and negation, \d \D \w \W \s \S \b \B and common literal escapes, groups,
// alternation, and the greedy quantifiers * + ? {m} {m,} {m,n}. Trailing '?'
// (non-greedy) is consumed and ignored — a boolean .test() cannot observe the
// difference. Lookaround and backreferences are rejected as invalid patterns.

#[derive(Debug, Clone)]
enum Ast {
    Alt(Vec<Vec<Ast>>),
    Rep(Box<Ast>, usize, usize),
    Char(char),
    Any,
    Start,
    End,
    WordB(bool),
    Class(bool, Vec<(char, char)>),
    Group(Box<Ast>),
}

const INF: usize = usize::MAX;

fn word_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || c == '_'
}

fn esc_ranges(e: char) -> Option<Vec<(char, char)>> {
    Some(match e {
        'd' => vec![('0', '9')],
        'D' => return None, // complemented shorthand in a class: unsupported
        'w' => vec![('A', 'Z'), ('a', 'z'), ('0', '9'), ('_', '_')],
        'W' => return None,
        's' => vec![(' ', ' '), ('\t', '\t'), ('\n', '\n'), ('\r', '\r'), ('\u{b}', '\u{b}'), ('\u{c}', '\u{c}')],
        'S' => return None,
        'n' => vec![('\n', '\n')],
        't' => vec![('\t', '\t')],
        'r' => vec![('\r', '\r')],
        'f' => vec![('\u{c}', '\u{c}')],
        'v' => vec![('\u{b}', '\u{b}')],
        c => vec![(c, c)],
    })
}

fn parse_alt(p: &[char], i: &mut usize) -> Result<Ast, ()> {
    let mut branches = vec![parse_concat(p, i)?];
    while *i < p.len() && p[*i] == '|' {
        *i += 1;
        branches.push(parse_concat(p, i)?);
    }
    Ok(Ast::Alt(branches))
}

fn parse_concat(p: &[char], i: &mut usize) -> Result<Vec<Ast>, ()> {
    let mut out = Vec::new();
    while *i < p.len() && p[*i] != '|' && p[*i] != ')' {
        out.push(parse_repeat(p, i)?);
    }
    Ok(out)
}

fn parse_repeat(p: &[char], i: &mut usize) -> Result<Ast, ()> {
    let atom = parse_atom(p, i)?;
    let (min, max) = match p.get(*i) {
        Some('*') => {
            *i += 1;
            (0, INF)
        }
        Some('+') => {
            *i += 1;
            (1, INF)
        }
        Some('?') => {
            *i += 1;
            (0, 1)
        }
        Some('{') => {
            let save = *i;
            *i += 1;
            let lo = parse_int(p, i);
            let bound = if p.get(*i) == Some(&',') {
                *i += 1;
                parse_int(p, i).map_or(INF, |n| n)
            } else {
                lo.unwrap_or(INF)
            };
            match (lo, p.get(*i) == Some(&'}')) {
                (Some(lo), true) => {
                    *i += 1;
                    (lo, bound)
                }
                _ => {
                    *i = save; // unmatched '{' is a literal, like JS
                    return Ok(atom);
                }
            }
        }
        _ => return Ok(atom),
    };
    if p.get(*i) == Some(&'?') {
        *i += 1; // non-greedy flag: ignored (boolean test)
    }
    Ok(Ast::Rep(Box::new(atom), min, max))
}

fn parse_int(p: &[char], i: &mut usize) -> Option<usize> {
    let start = *i;
    while p.get(*i).map_or(false, |c| c.is_ascii_digit()) {
        *i += 1;
    }
    if start == *i {
        return None;
    }
    p[start..*i].iter().collect::<String>().parse().ok()
}

fn parse_atom(p: &[char], i: &mut usize) -> Result<Ast, ()> {
    match *p.get(*i).ok_or(())? {
        '.' => {
            *i += 1;
            Ok(Ast::Any)
        }
        '^' => {
            *i += 1;
            Ok(Ast::Start)
        }
        '$' => {
            *i += 1;
            Ok(Ast::End)
        }
        '(' => {
            *i += 1;
            if p.get(*i) == Some(&'?') {
                if p.get(*i + 1) == Some(&':') {
                    *i += 2;
                } else {
                    return Err(()); // lookaround etc: unsupported
                }
            }
            let inner = parse_alt(p, i)?;
            if p.get(*i) != Some(&')') {
                return Err(());
            }
            *i += 1;
            Ok(Ast::Group(Box::new(inner)))
        }
        '[' => parse_class(p, i),
        '\\' => {
            *i += 1;
            let e = *p.get(*i).ok_or(())?;
            *i += 1;
            Ok(match e {
                'd' => Ast::Class(false, vec![('0', '9')]),
                'D' => Ast::Class(true, vec![('0', '9')]),
                'w' => Ast::Class(false, vec![('A', 'Z'), ('a', 'z'), ('0', '9'), ('_', '_')]),
                'W' => Ast::Class(true, vec![('A', 'Z'), ('a', 'z'), ('0', '9'), ('_', '_')]),
                's' => Ast::Class(false, vec![(' ', ' '), ('\t', '\t'), ('\n', '\n'), ('\r', '\r'), ('\u{b}', '\u{b}'), ('\u{c}', '\u{c}')]),
                'S' => Ast::Class(true, vec![(' ', ' '), ('\t', '\t'), ('\n', '\n'), ('\r', '\r'), ('\u{b}', '\u{b}'), ('\u{c}', '\u{c}')]),
                'b' => Ast::WordB(true),
                'B' => Ast::WordB(false),
                'n' => Ast::Char('\n'),
                't' => Ast::Char('\t'),
                'r' => Ast::Char('\r'),
                'f' => Ast::Char('\u{c}'),
                'v' => Ast::Char('\u{b}'),
                '0' => Ast::Char('\0'),
                c => Ast::Char(c),
            })
        }
        ')' => Err(()),
        _ => {
            let c = p[*i];
            *i += 1;
            Ok(Ast::Char(c))
        }
    }
}

fn parse_class(p: &[char], i: &mut usize) -> Result<Ast, ()> {
    *i += 1; // '['
    let neg = p.get(*i) == Some(&'^');
    if neg {
        *i += 1;
    }
    let mut ranges: Vec<(char, char)> = Vec::new();
    let mut first = true;
    while *i < p.len() {
        let mut lo = p[*i];
        if lo == ']' && !first {
            *i += 1;
            return Ok(Ast::Class(neg, ranges));
        }
        first = false;
        if lo == '\\' {
            *i += 1;
            let ranges2 = esc_ranges(*p.get(*i).ok_or(())?).ok_or(())?;
            *i += 1;
            if ranges2.len() != 1 {
                return Err(());
            }
            lo = ranges2[0].0;
        } else {
            *i += 1;
        }
        if p.get(*i) == Some(&'-') && p.get(*i + 1) != Some(&']') && *i + 1 < p.len() {
            *i += 1;
            let mut hi = *p.get(*i).ok_or(())?;
            if hi == '\\' {
                *i += 1;
                let ranges2 = esc_ranges(*p.get(*i).ok_or(())?).ok_or(())?;
                *i += 1;
                if ranges2.len() != 1 {
                    return Err(());
                }
                hi = ranges2[0].0;
            } else {
                *i += 1;
            }
            ranges.push((lo, hi));
        } else {
            ranges.push((lo, lo));
        }
    }
    Err(()) // unterminated class
}

fn compile_regex(pat: &str) -> Option<Ast> {
    let chars: Vec<char> = pat.chars().collect();
    let mut i = 0;
    match parse_alt(&chars, &mut i) {
        Ok(ast) if i == chars.len() => Some(ast),
        _ => None,
    }
}

fn m(a: &Ast, t: &[char], pos: usize, k: &mut dyn FnMut(usize) -> bool) -> bool {
    match a {
        Ast::Char(c) => pos < t.len() && t[pos] == *c && k(pos + 1),
        Ast::Any => {
            pos < t.len() && t[pos] != '\n' && t[pos] != '\r' && k(pos + 1)
        }
        Ast::Start => pos == 0 && k(pos),
        Ast::End => pos == t.len() && k(pos),
        Ast::WordB(want) => {
            let before = pos > 0 && word_char(t[pos - 1]);
            let after = pos < t.len() && word_char(t[pos]);
            ((before != after) == *want) && k(pos)
        }
        Ast::Class(neg, ranges) => {
            if pos >= t.len() {
                return false;
            }
            let c = t[pos];
            let hit = ranges.iter().any(|&(lo, hi)| c >= lo && c <= hi);
            (hit != *neg) && k(pos + 1)
        }
        Ast::Group(inner) => m(inner, t, pos, k),
        Ast::Alt(branches) => branches.iter().any(|seq| m_seq(seq, 0, t, pos, k)),
        Ast::Rep(inner, min, max) => m_rep(inner, 0, *min, *max, t, pos, k),
    }
}

fn m_seq(seq: &[Ast], i: usize, t: &[char], pos: usize, k: &mut dyn FnMut(usize) -> bool) -> bool {
    if i == seq.len() {
        return k(pos);
    }
    m(&seq[i], t, pos, &mut |np| m_seq(seq, i + 1, t, np, k))
}

fn m_rep(inner: &Ast, done: usize, min: usize, max: usize, t: &[char], pos: usize, k: &mut dyn FnMut(usize) -> bool) -> bool {
    if done < max
        && m(inner, t, pos, &mut |np| {
            np != pos && m_rep(inner, done + 1, min, max, t, np, k)
        })
    {
        return true;
    }
    if done >= min {
        return k(pos);
    }
    false
}

// JS `new RegExp(p).test(v)` — unanchored boolean search.
fn js_regex_test(ast: &Ast, text: &str) -> bool {
    let t: Vec<char> = text.chars().collect();
    (0..=t.len()).any(|start| m(ast, &t, start, &mut |_| true))
}

// ---- validator -----------------------------------------------------------------------

fn obj_get<'a>(o: &'a [(String, JVal)], key: &str) -> Option<&'a JVal> {
    o.iter().find(|(k, _)| k == key).map(|(_, v)| v)
}

fn validate(v: &JVal, schema: &JVal, path: &str, r: &mut Result) {
    match schema {
        JVal::Bool(false) => {
            r.issues.push(Issue {
                path: path.to_string(),
                message: "no value is allowed here (schema is false)".to_string(),
            });
            return;
        }
        JVal::Bool(true) => return,
        JVal::Obj(s) => {
            walk(v, s, path, r);
        }
        _ => r.issues.push(Issue {
            path: path.to_string(),
            message: "invalid schema node: expected an object or boolean".to_string(),
        }),
    }
}

fn walk(v: &JVal, s: &[(String, JVal)], path: &str, r: &mut Result) {
    let mut issue = |p: &str, msg: String| {
        r.issues.push(Issue { path: p.to_string(), message: msg });
    };

    if let Some(t) = obj_get(s, "type") {
        let allowed: Vec<String> = match t {
            JVal::Arr(entries) => entries.iter().map(js_str).collect(),
            other => vec![js_str(other)],
        };
        let actual = kind_of(v);
        let ok = allowed
            .iter()
            .any(|t| t == actual || (t == "number" && actual == "integer"));
        if !ok {
            issue(path, format!("expected type {}, got {}", allowed.join("|"), actual));
        }
    }

    if let Some(JVal::Arr(list)) = obj_get(s, "enum") {
        if !list.iter().any(|e| deep_equal(v, e)) {
            issue(path, format!("value not in enum ({} allowed)", list.len()));
        }
    }

    if let Some(k) = obj_get(s, "const") {
        if !deep_equal(v, k) {
            issue(path, "value does not match const".to_string());
        }
    }

    if let JVal::Num(dv) = v {
        for (key, msg, cmp) in [
            ("minimum", "is less than minimum", 0),
            ("maximum", "is greater than maximum", 1),
            ("exclusiveMinimum", "is not greater than exclusiveMinimum", 2),
            ("exclusiveMaximum", "is not less than exclusiveMaximum", 3),
        ] {
            if let Some(JVal::Num(mv)) = obj_get(s, key) {
                let violated = match cmp {
                    0 => dv < mv,
                    1 => dv > mv,
                    2 => dv <= mv,
                    _ => dv >= mv,
                };
                if violated {
                    issue(path, format!("{} {} {}", js_num(*dv), msg, js_num(*mv)));
                }
            }
        }
    }

    if let JVal::Str(sv) = v {
        let len = utf16_len(sv);
        for (key, msg, is_min) in
            [("minLength", "is less than minLength", true), ("maxLength", "is greater than maxLength", false)]
        {
            if let Some(JVal::Num(mv)) = obj_get(s, key) {
                let violated = if is_min {
                    (len as f64) < *mv
                } else {
                    (len as f64) > *mv
                };
                if violated {
                    issue(path, format!("string length {} {} {}", len, msg, js_num(*mv)));
                }
            }
        }
        if let Some(JVal::Str(pat)) = obj_get(s, "pattern") {
            match compile_regex(pat) {
                Some(ast) => {
                    if !js_regex_test(&ast, sv) {
                        issue(path, format!("string does not match pattern {}", pat));
                    }
                }
                None => issue(path, format!("invalid pattern in schema: {}", pat)),
            }
        }
    }

    if let JVal::Arr(av) = v {
        for (key, msg, is_min) in
            [("minItems", "is less than minItems", true), ("maxItems", "is greater than maxItems", false)]
        {
            if let Some(JVal::Num(mv)) = obj_get(s, key) {
                let violated = if is_min {
                    (av.len() as f64) < *mv
                } else {
                    (av.len() as f64) > *mv
                };
                if violated {
                    issue(path, format!("array length {} {} {}", av.len(), msg, js_num(*mv)));
                }
            }
        }
        if obj_get(s, "uniqueItems") == Some(&JVal::Bool(true)) {
            for i in 0..av.len() {
                for j in (i + 1)..av.len() {
                    if deep_equal(&av[i], &av[j]) {
                        issue(
                            &format!("{}[{}]", path, j),
                            format!("duplicate item (same as index {})", i),
                        );
                    }
                }
            }
        }
        if let Some(items) = obj_get(s, "items") {
            for (i, item) in av.iter().enumerate() {
                let p = format!("{}[{}]", path, i);
                validate(item, items, &p, r);
            }
        }
    }

    if let JVal::Obj(ov) = v {
        if let Some(JVal::Arr(req)) = obj_get(s, "required") {
            for rk in req {
                let key = js_str(rk);
                if obj_get(ov, &key).is_none() {
                    issue(path, format!("missing required property \"{}\"", key));
                }
            }
        }
        let props = match obj_get(s, "properties") {
            Some(JVal::Obj(p)) => Some(p),
            _ => None,
        };
        if let Some(props) = props {
            for (key, sub) in props {
                if let Some(subv) = obj_get(ov, key) {
                    let p = format!("{}.{}", path, key);
                    validate(subv, sub, &p, r);
                }
            }
        }
        if obj_get(s, "additionalProperties") == Some(&JVal::Bool(false)) {
            for (key, _) in ov {
                let known = props.map_or(false, |p| obj_get(p, key).is_some());
                if !known {
                    issue(&format!("{}.{}", path, key), "additional property not allowed".to_string());
                }
            }
        }
    }
}

fn blank(s: &str) -> bool {
    s.trim().is_empty()
}

/** Validate a JSON document against a schema. */
pub fn validate_json_schema(schema_raw: &str, instance_raw: &str) -> Result {
    let mut r = Result::default();
    if blank(schema_raw) || blank(instance_raw) {
        r.error = Some("Both a schema and an instance are required".to_string());
        return r;
    }
    let mut ps = P { b: schema_raw.as_bytes(), i: 0 };
    let schema = match ps.value() {
        Some(v) if ps.peek().is_none() => v,
        _ => {
            r.error = Some("Schema: Invalid JSON".to_string());
            return r;
        }
    };
    let mut pi = P { b: instance_raw.as_bytes(), i: 0 };
    let instance = match pi.value() {
        Some(v) if pi.peek().is_none() => v,
        _ => {
            r.error = Some("Instance: Invalid JSON".to_string());
            return r;
        }
    };
    validate(&instance, &schema, "$", &mut r);
    r.valid = r.issues.is_empty();
    r
}

// Example:
// validate_json_schema(
//     r#"{"type":"object","required":["port"],"properties":{"port":{"type":"integer","minimum":1024}}}"#,
//     r#"{"port":80}"#).issues[0].message
// → "80 is less than minimum 1024"

fn main() {
    let r = validate_json_schema(
        "{\"type\":\"object\",\"required\":[\"port\"],\"properties\":{\"port\":{\"type\":\"integer\",\"minimum\":1024}}}",
        "{\"port\":80}");
    println!("valid={} issues={} error={}", r.valid, r.issues.len(), r.error.as_deref().unwrap_or("null"));
    for i in &r.issues {
        println!("  {}: {}", i.path, i.message);
    }
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →