Skip to content

JSON to JSON Schema Generator — C++ 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 C++ implementation — the same logic the interactive tool runs, in a shareable, citable form.

// json-to-schema — JSON instance → draft-07 JSON Schema inferrer. C++ port
// (canonical TS: src/lib/json-to-schema.ts; Go twin: cli/json-to-schema).
// Given one JSON instance, infers a draft-07 style schema: 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 mode adds
// "additionalProperties": false to every object schema. Empty or
// whitespace-only input yields empty output, not an error; parse failures
// carry a message in Result.error. Output is a hand-rolled 2-space pretty
// print with JSON.stringify(schema, null, 2) parity.
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <optional>
#include <string>
#include <utility>
#include <vector>

namespace {

constexpr const char *kDraft07 = "http://json-schema.org/draft-07/schema#";

// ---- JSON value tree (document order; duplicate keys keep the last value) ----

struct Json {
    enum class Kind { Null, Bool, Num, Str, Arr, Obj } kind = Kind::Null;
    bool boolean = false;
    double number = 0.0;
    std::string str;
    std::vector<Json> items;                          // Arr
    std::vector<std::pair<std::string, Json>> members; // Obj
};

// ---- recursive-descent parser mirroring JSON.parse ----

struct Parser {
    const std::string &src;
    size_t pos = 0;
    bool failed = false;

    void ws() {
        while (pos < src.size() &&
               (src[pos] == ' ' || src[pos] == '\t' || src[pos] == '\n' || src[pos] == '\r'))
            pos++;
    }
    char peek() const { return pos < src.size() ? src[pos] : '\0'; }

    std::string stringRaw() {
        std::string out;
        if (peek() != '"') { failed = true; return out; }
        pos++;
        auto pushUtf8 = [&out](unsigned cp) {
            if (cp < 0x80) out += static_cast<char>(cp);
            else if (cp < 0x800) {
                out += static_cast<char>(0xC0 | (cp >> 6));
                out += static_cast<char>(0x80 | (cp & 0x3F));
            } else {
                out += static_cast<char>(0xE0 | (cp >> 12));
                out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
                out += static_cast<char>(0x80 | (cp & 0x3F));
            }
        };
        auto hex4 = [&](size_t at) -> int { // code point, or -1 on bad hex
            if (at + 4 > src.size()) return -1;
            unsigned cp = 0;
            for (size_t i = 0; i < 4; i++) {
                char c = src[at + i];
                cp <<= 4;
                if (c >= '0' && c <= '9') cp |= static_cast<unsigned>(c - '0');
                else if (c >= 'a' && c <= 'f') cp |= static_cast<unsigned>(c - 'a' + 10);
                else if (c >= 'A' && c <= 'F') cp |= static_cast<unsigned>(c - 'A' + 10);
                else return -1;
            }
            return static_cast<int>(cp);
        };
        while (pos < src.size() && src[pos] != '"') {
            char c = src[pos];
            if (c == '\\') {
                pos++;
                switch (peek()) {
                case '"': out += '"'; break;
                case '\\': out += '\\'; break;
                case '/': out += '/'; break;
                case 'b': out += '\b'; break;
                case 'f': out += '\f'; break;
                case 'n': out += '\n'; break;
                case 'r': out += '\r'; break;
                case 't': out += '\t'; break;
                case 'u': {
                    int cp = hex4(pos + 1);
                    if (cp < 0) { failed = true; return out; }
                    pos += 5;
                    // Combine surrogate pairs; a lone surrogate re-encodes as
                    // 3 bytes (String cannot hold it as-is), like the C port.
                    if (cp >= 0xD800 && cp <= 0xDBFF && peek() == '\\' &&
                        pos + 1 < src.size() && src[pos + 1] == 'u') {
                        int lo = hex4(pos + 2);
                        if (lo >= 0xDC00 && lo <= 0xDFFF) {
                            cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
                            pos += 6;
                        }
                    }
                    pushUtf8(static_cast<unsigned>(cp));
                    break;
                }
                default: failed = true; return out;
                }
                pos++;
            } else if (static_cast<unsigned char>(c) < 0x20) {
                failed = true; // unescaped control character
                return out;
            } else {
                out += c; // raw UTF-8 passes through
                pos++;
            }
        }
        if (peek() != '"') { failed = true; return out; }
        pos++;
        return out;
    }

    // Strict JSON number grammar (JSON.parse rejects "01", "1.", ".5", "+1");
    // strtod overflow yields HUGE_VAL, like JS's Infinity.
    bool number(double &out) {
        size_t q = pos;
        if (q < src.size() && src[q] == '-') q++;
        if (q < src.size() && src[q] == '0') q++;
        else if (q < src.size() && src[q] >= '1' && src[q] <= '9') {
            while (q < src.size() && src[q] >= '0' && src[q] <= '9') q++;
        } else return false;
        if (q < src.size() && src[q] == '.') {
            q++;
            if (q >= src.size() || src[q] < '0' || src[q] > '9') return false;
            while (q < src.size() && src[q] >= '0' && src[q] <= '9') q++;
        }
        if (q < src.size() && (src[q] == 'e' || src[q] == 'E')) {
            q++;
            if (q < src.size() && (src[q] == '+' || src[q] == '-')) q++;
            if (q >= src.size() || src[q] < '0' || src[q] > '9') return false;
            while (q < src.size() && src[q] >= '0' && src[q] <= '9') q++;
        }
        out = std::strtod(src.c_str() + pos, nullptr);
        pos = q;
        return true;
    }

    Json value() {
        Json v;
        ws();
        char c = peek();
        if (c == '{') {
            pos++;
            v.kind = Json::Kind::Obj;
            ws();
            if (peek() == '}') { pos++; return v; }
            for (;;) {
                ws();
                std::string key = stringRaw();
                if (failed) return v;
                ws();
                if (peek() != ':') { failed = true; return v; }
                pos++;
                Json val = value();
                if (failed) return v;
                // duplicate key: last wins, keeps its first position
                size_t found = v.members.size();
                for (size_t i = 0; i < v.members.size(); i++)
                    if (v.members[i].first == key) { found = i; break; }
                if (found < v.members.size()) v.members[found].second = std::move(val);
                else v.members.emplace_back(std::move(key), std::move(val));
                ws();
                if (peek() == ',') { pos++; continue; }
                if (peek() == '}') { pos++; return v; }
                failed = true;
                return v;
            }
        }
        if (c == '[') {
            pos++;
            v.kind = Json::Kind::Arr;
            ws();
            if (peek() == ']') { pos++; return v; }
            for (;;) {
                Json el = value();
                if (failed) return v;
                v.items.push_back(std::move(el));
                ws();
                if (peek() == ',') { pos++; continue; }
                if (peek() == ']') { pos++; return v; }
                failed = true;
                return v;
            }
        }
        if (c == '"') {
            std::string s = stringRaw();
            if (failed) return v;
            v.kind = Json::Kind::Str;
            v.str = std::move(s);
            return v;
        }
        if (src.compare(pos, 4, "true") == 0) {
            pos += 4;
            v.kind = Json::Kind::Bool;
            v.boolean = true;
            return v;
        }
        if (src.compare(pos, 5, "false") == 0) {
            pos += 5;
            v.kind = Json::Kind::Bool;
            return v;
        }
        if (src.compare(pos, 4, "null") == 0) { pos += 4; return v; }
        double n;
        if (number(n)) {
            v.kind = Json::Kind::Num;
            v.number = n;
            return v;
        }
        failed = true;
        return v;
    }

    Json top() {
        Json v = value();
        if (failed) return v;
        ws();
        if (pos != src.size()) failed = true; // trailing content
        return v;
    }
};

// ---- schema inference ----

const char *scalarKind(const Json &v) {
    switch (v.kind) {
    case Json::Kind::Arr: return "array";
    case Json::Kind::Null: return "null";
    case Json::Kind::Bool: return "boolean";
    case Json::Kind::Num:
        // JSON has no int type: an integral double (2.0, 1e2) is an integer.
        return std::isfinite(v.number) && v.number == std::floor(v.number) ? "integer" : "number";
    case Json::Kind::Obj: return "object";
    default: return "string";
    }
}

using Members = std::vector<std::pair<std::string, Json>>;

Json objNode(Members members) {
    Json v;
    v.kind = Json::Kind::Obj;
    v.members = std::move(members);
    return v;
}

Json strNode(const std::string &s) { return {Json::Kind::Str, false, 0.0, s, {}, {}}; }

Json boolNode(bool b) { return {Json::Kind::Bool, b, 0.0, "", {}, {}}; }

Json scalarSchema(const std::string &type) { return objNode({{"type", strNode(type)}}); }

// Sorted unique type list for a merged schema.
std::vector<std::string> sortedKinds(const Json &arr) {
    std::vector<std::string> kinds;
    for (const Json &el : arr.items) {
        const char *k = scalarKind(el);
        if (std::find(kinds.begin(), kinds.end(), k) == kinds.end()) kinds.push_back(k);
    }
    std::sort(kinds.begin(), kinds.end());
    return kinds;
}

Json infer(const Json &v, bool strict) {
    if (v.kind == Json::Kind::Arr) {
        if (v.items.empty()) return scalarSchema("array"); // carries no `items` key
        std::vector<std::string> types = sortedKinds(v);
        Json items;
        if (types.size() == 1) {
            items = scalarSchema(types[0]);
        } else {
            Json list;
            list.kind = Json::Kind::Arr;
            for (const std::string &t : types) list.items.push_back(strNode(t));
            items = objNode({{"type", std::move(list)}});
        }
        return objNode({{"type", strNode("array")}, {"items", std::move(items)}});
    }
    if (v.kind == Json::Kind::Obj) {
        std::vector<std::string> keys;
        for (const auto &m : v.members) keys.push_back(m.first);
        std::sort(keys.begin(), keys.end()); // byte order, like JS default sort
        Members properties;
        for (const std::string &k : keys) {
            for (const auto &m : v.members)
                if (m.first == k) { properties.emplace_back(k, infer(m.second, strict)); break; }
        }
        Json reqList; // `required` is a JSON array of plain strings
        reqList.kind = Json::Kind::Arr;
        for (const std::string &k : keys) reqList.items.push_back(strNode(k));
        Members schema;
        schema.emplace_back("type", strNode("object"));
        schema.emplace_back("properties", objNode(std::move(properties)));
        schema.emplace_back("required", std::move(reqList));
        if (strict) schema.emplace_back("additionalProperties", boolNode(false));
        return objNode(std::move(schema));
    }
    return scalarSchema(scalarKind(v));
}

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

void dumpString(std::string &out, const std::string &s) {
    out += '"';
    for (unsigned char c : s) {
        switch (c) {
        case '"': out += "\\\""; break;
        case '\\': out += "\\\\"; break;
        case '\b': out += "\\b"; break;
        case '\f': out += "\\f"; break;
        case '\n': out += "\\n"; break;
        case '\r': out += "\\r"; break;
        case '\t': out += "\\t"; break;
        default:
            if (c < 0x20) {
                char esc[8];
                std::snprintf(esc, sizeof esc, "\\u%04x", static_cast<unsigned>(c));
                out += esc;
            } else {
                out += static_cast<char>(c); // raw UTF-8 passes through, like JS
            }
        }
    }
    out += '"';
}

void dump(std::string &out, const Json &v, size_t indent) {
    const std::string pad(indent * 2, ' ');
    if (v.kind == Json::Kind::Obj) {
        if (v.members.empty()) { out += "{}"; return; }
        out += "{\n";
        bool first = true;
        for (const auto &m : v.members) {
            if (!first) out += ",\n";
            first = false;
            out += pad;
            out += "  ";
            dumpString(out, m.first);
            out += ": ";
            dump(out, m.second, indent + 1);
        }
        out += '\n';
        out += pad;
        out += '}';
    } else if (v.kind == Json::Kind::Arr) {
        if (v.items.empty()) { out += "[]"; return; }
        out += "[\n";
        bool first = true;
        for (const Json &el : v.items) {
            if (!first) out += ",\n";
            first = false;
            out += pad;
            out += "  ";
            dump(out, el, indent + 1);
        }
        out += '\n';
        out += pad;
        out += ']';
    } else if (v.kind == Json::Kind::Str) {
        dumpString(out, v.str);
    } else if (v.kind == Json::Kind::Bool) {
        out += v.boolean ? "true" : "false";
    } else {
        out += "null";
    }
}

bool isBlank(const std::string &s) {
    return s.find_first_not_of(" \t\n\r") == std::string::npos;
}

} // namespace

struct JsonToSchemaResult {
    std::string output;
    std::optional<std::string> error; // nullopt on success
};

JsonToSchemaResult jsonToSchema(const std::string &raw, bool strictObjects = false) {
    JsonToSchemaResult res;
    // top() skips surrounding whitespace itself, so a blank-check on raw is
    // all the trimming needed: whitespace-only input yields empty output.
    if (isBlank(raw)) { res.output = ""; return res; } // NOT an error
    Parser p{raw, 0, false};
    Json value = p.top();
    if (p.failed) { res.error = "Invalid JSON"; return res; }
    Json root;
    root.kind = Json::Kind::Obj;
    root.members.emplace_back("$schema", strNode(kDraft07));
    Json body = infer(value, strictObjects);
    for (auto &m : body.members) root.members.push_back(std::move(m));
    std::string out;
    dump(out, root, 0);
    res.output = out;
    return res;
}

// Example:
// jsonToSchema(R"({"b": 1, "a": [1, "x"]})").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 →