Skip to content

JSON to JSON Schema Generator — Rust source

Infer a draft-07 JSON Schema from any JSON document: scalar types, array item merging, all-keys-required objects and an optional strict mode. Runs locally in your browser with a shareable link.

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

//! json-to-schema — JSON instance → draft-07 JSON Schema inferrer. Rust port
//! (canonical TS: `src/lib/json-to-schema.ts`; Go twin: `cli/json-to-schema`).
//! Hand-rolled strict JSON parser (no external crates) + schema inference:
//! the integer vs number split (2.0 is an integer — JSON has no int type),
//! objects list every key as required with keys sorted, homogeneous arrays
//! merge to a single item type, mixed arrays become a sorted `type` array
//! (other keywords dropped), empty arrays carry no `items` key, and
//! `strict_objects` adds "additionalProperties": false to every object
//! schema. Empty or whitespace-only input yields empty output, not an error;
//! parse failures surface the parser's message via `Result.error`. Output is
//! a hand-rolled 2-space pretty print with JSON.stringify(schema, null, 2)
//! parity. Never panics on malformed input.

const DRAFT_07: &str = "http://json-schema.org/draft-07/schema#";

#[derive(Clone, Debug)]
pub enum Json {
    Null,
    Bool(bool),
    Num(f64),
    Str(String),
    Arr(Vec<Json>),
    Obj(Vec<(String, Json)>), // insertion order preserved; duplicate key keeps last
}

pub struct ParseError(pub &'static str);

struct Parser<'a> {
    src: &'a [u8],
    pos: usize,
}

impl<'a> Parser<'a> {
    fn new(src: &'a str) -> Self {
        Parser { src: src.as_bytes(), pos: 0 }
    }

    fn peek(&self) -> Option<u8> {
        self.src.get(self.pos).copied()
    }

    fn fail<T>(&self, msg: &'static str) -> Result<T, ParseError> {
        Err(ParseError(msg))
    }

    fn ws(&mut self) {
        while matches!(self.peek(), Some(b' ' | b'\t' | b'\n' | b'\r')) {
            self.pos += 1;
        }
    }

    fn digit(c: u8) -> bool {
        c.is_ascii_digit()
    }

    fn hex4(&mut self) -> Result<u32, ParseError> {
        let mut v: u32 = 0;
        for _ in 0..4 {
            let c = self.peek().ok_or(ParseError("Bad \\u escape"))?;
            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 self.fail("Bad \\u escape"),
            };
            v = v * 16 + d;
            self.pos += 1;
        }
        Ok(v)
    }

    fn utf8_push(out: &mut Vec<u8>, cp: u32) {
        if cp < 0x80 {
            out.push(cp as u8);
        } else if cp < 0x800 {
            out.push(0xC0 | (cp >> 6) as u8);
            out.push(0x80 | (cp & 0x3F) as u8);
        } else if cp < 0x10000 {
            out.push(0xE0 | (cp >> 12) as u8);
            out.push(0x80 | ((cp >> 6) & 0x3F) as u8);
            out.push(0x80 | (cp & 0x3F) as u8);
        } else {
            out.push(0xF0 | (cp >> 18) as u8);
            out.push(0x80 | ((cp >> 12) & 0x3F) as u8);
            out.push(0x80 | ((cp >> 6) & 0x3F) as u8);
            out.push(0x80 | (cp & 0x3F) as u8);
        }
    }

    fn string(&mut self) -> Result<String, ParseError> {
        self.pos += 1; // opening quote
        let mut out: Vec<u8> = Vec::new();
        loop {
            let c = match self.peek() {
                Some(c) => c,
                None => return self.fail("Unterminated string"),
            };
            match c {
                b'"' => {
                    self.pos += 1;
                    break;
                }
                b'\\' => {
                    self.pos += 1;
                    let e = match self.peek() {
                        Some(e) => e,
                        None => return self.fail("Unterminated string"),
                    };
                    match e {
                        b'"' => out.push(b'"'),
                        b'\\' => out.push(b'\\'),
                        b'/' => out.push(b'/'),
                        b'b' => out.push(0x08),
                        b'f' => out.push(0x0C),
                        b'n' => out.push(b'\n'),
                        b'r' => out.push(b'\r'),
                        b't' => out.push(b'\t'),
                        b'u' => {
                            self.pos += 1;
                            let mut cp = self.hex4()?;
                            if (0xD800..=0xDBFF).contains(&cp) {
                                if self.peek() == Some(b'\\') && self.src.get(self.pos + 1) == Some(&b'u') {
                                    self.pos += 2;
                                    let lo = self.hex4()?;
                                    if (0xDC00..=0xDFFF).contains(&lo) {
                                        cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
                                    } else {
                                        cp = 0xFFFD;
                                        self.pos -= 2; // second \u handled next round
                                    }
                                } else {
                                    cp = 0xFFFD;
                                }
                            } else if (0xDC00..=0xDFFF).contains(&cp) {
                                cp = 0xFFFD;
                            }
                            Self::utf8_push(&mut out, cp);
                            continue;
                        }
                        _ => return self.fail("Bad escape"),
                    }
                    self.pos += 1;
                }
                _ => {
                    out.push(c);
                    self.pos += 1;
                }
            }
        }
        // Bytes are valid UTF-8 by construction.
        String::from_utf8(out).map_err(|_| ParseError("Bad string"))
    }

    fn number(&mut self) -> Result<Json, ParseError> {
        let start = self.pos;
        if self.peek() == Some(b'-') {
            self.pos += 1;
        }
        match self.peek() {
            Some(c) if Self::digit(c) => {}
            _ => return self.fail("Invalid number"),
        }
        if self.peek() == Some(b'0') {
            self.pos += 1;
        } else {
            while matches!(self.peek(), Some(c) if Self::digit(c)) {
                self.pos += 1;
            }
        }
        if self.peek() == Some(b'.') {
            self.pos += 1;
            match self.peek() {
                Some(c) if Self::digit(c) => {}
                _ => return self.fail("Invalid number"),
            }
            while matches!(self.peek(), Some(c) if Self::digit(c)) {
                self.pos += 1;
            }
        }
        if matches!(self.peek(), Some(b'e' | b'E')) {
            self.pos += 1;
            if matches!(self.peek(), Some(b'+' | b'-')) {
                self.pos += 1;
            }
            match self.peek() {
                Some(c) if Self::digit(c) => {}
                _ => return self.fail("Invalid number"),
            }
            while matches!(self.peek(), Some(c) if Self::digit(c)) {
                self.pos += 1;
            }
        }
        let text = std::str::from_utf8(&self.src[start..self.pos])
            .map_err(|_| ParseError("Invalid number"))?;
        let d = text.parse::<f64>().map_err(|_| ParseError("Invalid number"))?;
        Ok(Json::Num(d))
    }

    fn value(&mut self) -> Result<Json, ParseError> {
        self.ws();
        let c = match self.peek() {
            Some(c) => c,
            None => return self.fail("Unexpected token"),
        };
        match c {
            b'{' => self.object(),
            b'[' => self.array(),
            b'"' => self.string().map(Json::Str),
            b't' => {
                if self.src[self.pos..].starts_with(b"true") {
                    self.pos += 4;
                    Ok(Json::Bool(true))
                } else {
                    self.fail("Unexpected token")
                }
            }
            b'f' => {
                if self.src[self.pos..].starts_with(b"false") {
                    self.pos += 5;
                    Ok(Json::Bool(false))
                } else {
                    self.fail("Unexpected token")
                }
            }
            b'n' => {
                if self.src[self.pos..].starts_with(b"null") {
                    self.pos += 4;
                    Ok(Json::Null)
                } else {
                    self.fail("Unexpected token")
                }
            }
            c if Self::digit(c) || c == b'-' => self.number(),
            _ => self.fail("Unexpected token"),
        }
    }

    fn array(&mut self) -> Result<Json, ParseError> {
        self.pos += 1; // '['
        let mut items = Vec::new();
        self.ws();
        if self.peek() == Some(b']') {
            self.pos += 1;
            return Ok(Json::Arr(items));
        }
        loop {
            let el = self.value()?;
            items.push(el);
            self.ws();
            match self.peek() {
                Some(b',') => {
                    self.pos += 1;
                    self.ws();
                }
                Some(b']') => {
                    self.pos += 1;
                    return Ok(Json::Arr(items));
                }
                _ => return self.fail("Unexpected token"),
            }
        }
    }

    fn object(&mut self) -> Result<Json, ParseError> {
        self.pos += 1; // '{'
        let mut members: Vec<(String, Json)> = Vec::new();
        self.ws();
        if self.peek() == Some(b'}') {
            self.pos += 1;
            return Ok(Json::Obj(members));
        }
        loop {
            if self.peek() != Some(b'"') {
                return self.fail("Unexpected token");
            }
            let key = self.string()?;
            self.ws();
            if self.peek() != Some(b':') {
                return self.fail("Unexpected token");
            }
            self.pos += 1;
            self.ws();
            let val = self.value()?;
            // JSON objects keep the LAST value for a duplicate key (JSON.parse).
            match members.iter_mut().find(|(k, _)| *k == key) {
                Some((_, existing)) => *existing = val,
                None => members.push((key, val)),
            }
            self.ws();
            match self.peek() {
                Some(b',') => {
                    self.pos += 1;
                    self.ws();
                }
                Some(b'}') => {
                    self.pos += 1;
                    return Ok(Json::Obj(members));
                }
                _ => return self.fail("Unexpected token"),
            }
        }
    }

    fn document(&mut self) -> Result<Json, ParseError> {
        let v = self.value()?;
        self.ws();
        if self.pos != self.src.len() {
            return self.fail("Trailing characters");
        }
        Ok(v)
    }
}

/// Options: `strict_objects` adds "additionalProperties": false to every
/// object schema (default false — objects stay open).
#[derive(Clone, Copy, Debug, Default)]
pub struct JsonToSchemaOptions {
    pub strict_objects: bool,
}

#[derive(Debug)]
pub struct JsonToSchemaResult {
    /// Pretty-printed schema, 2-space (JSON.stringify(schema, null, 2)).
    pub output: String,
    /// `None` when inference succeeded (TS: error: null).
    pub error: Option<String>,
}

/// Schema tree preserving JSON.stringify insertion order.
#[derive(Clone, Debug)]
enum SchemaNode {
    Obj(Vec<(String, SchemaNode)>),
    Arr(Vec<SchemaNode>),
    Str(String),
    Bool(bool),
}

fn obj_get<'a>(o: &'a Json, key: &str) -> Option<&'a Json> {
    match o {
        Json::Obj(members) => members.iter().find(|(k, _)| k == key).map(|(_, v)| v),
        _ => None,
    }
}

/// Six scalar kinds. `Number.isInteger` parity: an integral double (2.0, 1e2)
/// is an "integer" — JSON has no int type — and non-finite overflow (1e400 →
/// Infinity) stays "number".
fn scalar_type(v: &Json) -> &'static str {
    match v {
        Json::Arr(_) => "array",
        Json::Null => "null",
        Json::Bool(_) => "boolean",
        Json::Num(d) => {
            if d.is_finite() && d.trunc() == *d { "integer" } else { "number" }
        }
        Json::Obj(_) => "object",
        Json::Str(_) => "string",
    }
}

fn scalar_schema(kind: &'static str) -> SchemaNode {
    SchemaNode::Obj(vec![("type".to_string(), SchemaNode::Str(kind.to_string()))])
}

/// Union of element kinds: one kind keeps it, else a sorted type list.
fn infer_array_items(v: &[Json]) -> SchemaNode {
    let mut kinds: Vec<&'static str> = Vec::new();
    for el in v {
        let k = scalar_type(el);
        if !kinds.contains(&k) {
            kinds.push(k);
        }
    }
    kinds.sort_unstable(); // JS default sort: code-unit order (kinds are ASCII)
    let type_node = if kinds.len() == 1 {
        SchemaNode::Str(kinds[0].to_string())
    } else {
        SchemaNode::Arr(kinds.iter().map(|k| SchemaNode::Str((*k).to_string())).collect())
    };
    SchemaNode::Obj(vec![
        ("type".to_string(), SchemaNode::Str("array".to_string())),
        ("items".to_string(), type_node),
    ])
}

fn infer(v: &Json, strict: bool) -> SchemaNode {
    match v {
        Json::Arr(items) => {
            if items.is_empty() {
                return scalar_schema("array"); // empty array carries no `items` key
            }
            infer_array_items(items)
        }
        Json::Obj(members) => {
            // duplicate keys are already collapsed (last wins) by the parser
            let mut keys: Vec<&str> = members.iter().map(|(k, _)| k.as_str()).collect();
            // String order = UTF-8 byte order = code point order; JS sort is
            // UTF-16 code-unit order — they differ only for astral keys.
            keys.sort();
            let mut properties: Vec<(String, SchemaNode)> = Vec::new();
            for key in &keys {
                let val = obj_get(v, key).expect("key exists");
                properties.push(((*key).to_string(), infer(val, strict)));
            }
            let mut entries: Vec<(String, SchemaNode)> = vec![
                ("type".to_string(), SchemaNode::Str("object".to_string())),
                ("properties".to_string(), SchemaNode::Obj(properties)),
                (
                    "required".to_string(),
                    SchemaNode::Arr(keys.iter().map(|k| SchemaNode::Str((*k).to_string())).collect()),
                ),
            ];
            if strict {
                entries.push(("additionalProperties".to_string(), SchemaNode::Bool(false)));
            }
            SchemaNode::Obj(entries)
        }
        _ => scalar_schema(scalar_type(v)),
    }
}

// ---- 2-space pretty printer (JSON.stringify(v, null, 2) parity) ----

fn dump_string(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\u{08}' => out.push_str("\\b"),
            '\u{0C}' => out.push_str("\\f"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
            c => out.push(c), // raw UTF-8 passes through, like JS
        }
    }
    out.push('"');
    out
}

fn dump(v: &SchemaNode, indent: usize) -> String {
    let pad = "  ".repeat(indent);
    match v {
        SchemaNode::Obj(entries) => {
            if entries.is_empty() {
                return "{}".to_string();
            }
            let parts: Vec<String> = entries
                .iter()
                .map(|(k, val)| format!("{}  {}: {}", pad, dump_string(k), dump(val, indent + 1)))
                .collect();
            format!("{{\n{}\n{}}}", parts.join(",\n"), pad)
        }
        SchemaNode::Arr(items) => {
            if items.is_empty() {
                return "[]".to_string();
            }
            let parts: Vec<String> = items
                .iter()
                .map(|el| format!("{}  {}", pad, dump(el, indent + 1)))
                .collect();
            format!("[\n{}\n{}]", parts.join(",\n"), pad)
        }
        SchemaNode::Str(s) => dump_string(s),
        SchemaNode::Bool(b) => {
            if *b { "true".to_string() } else { "false".to_string() }
        }
    }
}

/// Infer a draft-07 schema for the given JSON text, pretty-printed 2-space.
pub fn json_to_schema(raw: &str, options: &JsonToSchemaOptions) -> JsonToSchemaResult {
    let text = raw.trim();
    if text.is_empty() {
        // empty input is NOT an error — the tool shows nothing
        return JsonToSchemaResult { output: String::new(), error: None };
    }
    let mut parser = Parser::new(text);
    let value = match parser.document() {
        Ok(v) => v,
        Err(e) => {
            return JsonToSchemaResult { output: String::new(), error: Some(e.0.to_string()) };
        }
    };
    // { $schema: DRAFT_07, ...infer(value) } — infer's entries follow $schema.
    let mut entries: Vec<(String, SchemaNode)> =
        vec![("$schema".to_string(), SchemaNode::Str(DRAFT_07.to_string()))];
    if let SchemaNode::Obj(rest) = infer(&value, options.strict_objects) {
        entries.extend(rest);
    }
    JsonToSchemaResult { output: dump(&SchemaNode::Obj(entries), 0), error: None }
}

// Example:
// let r = json_to_schema(r#"{"b": 1, "a": [1, "x"]}"#, &JsonToSchemaOptions::default());
// assert!(r.error.is_none());
// // r.output:
// // {
// //   "$schema": "http://json-schema.org/draft-07/schema#",
// //   "type": "object",
// //   "properties": { "a": { "type": "array", "items": { "type": ["integer", "string"] } }, "b": { "type": "integer" } },
// //   "required": ["a", "b"]
// // }

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 →