JSON Schema Validator — C++ 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 C++ implementation — the same logic the interactive tool runs, in a shareable, citable form.
// json-schema-validator — draft-07 SUBSET JSON Schema validator. C++ 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. The C++ standard library ships no JSON parser,
// so this file carries a terse recursive-descent one; patterns run through
// std::regex with ECMAScript grammar. Integers are doubles flagged integral
// at validation time (Number.isInteger semantics). Numbers print into
// messages with JS Number-to-string rules via jsNum (70000, 1.5e-7, 1e+21).
// Vectors keep insertion order, so issue ordering matches the TS
// Object.keys walk. Never throws — errors travel in the result struct.
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <regex>
#include <string>
#include <vector>
namespace jsv {
enum Type { Null, Bool, Num, Str, Arr, Obj };
struct Val {
Type t = Null;
bool b = false;
double num = 0;
std::string s;
std::vector<Val> items; // Arr
std::vector<std::pair<std::string, Val>> pairs; // Obj, insertion order
};
struct Issue { std::string path, message; };
struct Result { bool valid = false; std::vector<Issue> issues; std::string error; };
// ---- JSON parser (recursive descent) ---------------------------------------
struct P {
const char *p;
void ws() { while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') p++; }
};
static void utf8_enc(std::string &s, unsigned cp) {
if (cp < 0x80) s += (char)cp;
else if (cp < 0x800) { s += (char)(0xC0 | (cp >> 6)); s += (char)(0x80 | (cp & 63)); }
else if (cp < 0x10000) { s += (char)(0xE0 | (cp >> 12)); s += (char)(0x80 | ((cp >> 6) & 63)); s += (char)(0x80 | (cp & 63)); }
else { s += (char)(0xF0 | (cp >> 18)); s += (char)(0x80 | ((cp >> 12) & 63)); s += (char)(0x80 | ((cp >> 6) & 63)); s += (char)(0x80 | (cp & 63)); }
}
static bool hex4(P &p, unsigned &out) {
out = 0;
for (int i = 0; i < 4; i++) {
char c = p.p[i];
out <<= 4;
if (c >= '0' && c <= '9') out |= (unsigned)(c - '0');
else if (c >= 'a' && c <= 'f') out |= (unsigned)(c - 'a' + 10);
else if (c >= 'A' && c <= 'F') out |= (unsigned)(c - 'A' + 10);
else return false;
}
p.p += 4;
return true;
}
static bool jstring(P &p, std::string &out) {
if (*p.p != '"') return false;
p.p++;
out.clear();
while (*p.p != '"') {
if (*p.p == '\\') {
p.p++;
switch (*p.p) {
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': {
unsigned cp;
if (!hex4(p, cp)) return false;
if (cp >= 0xD800 && cp <= 0xDBFF && p.p[1] == '\\' && p.p[2] == 'u') {
const char *save = p.p;
unsigned lo;
p.p += 2;
if (!hex4(p, lo) || lo < 0xDC00 || lo > 0xDFFF) { p.p = save; cp = 0xFFFD; }
else cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
} else if (cp >= 0xD800 && cp <= 0xDFFF) cp = 0xFFFD;
utf8_enc(out, cp);
continue;
}
default: return false;
}
p.p++;
} else if (!*p.p || (unsigned char)*p.p < 0x20) return false;
else out += *p.p++;
}
p.p++;
return true;
}
static bool jvalue(P &p, Val &v) {
p.ws();
if (!strncmp(p.p, "null", 4)) { p.p += 4; v = Val(); return true; }
if (!strncmp(p.p, "true", 4)) { p.p += 4; v = Val(); v.t = Bool; v.b = true; return true; }
if (!strncmp(p.p, "false", 5)) { p.p += 5; v = Val(); v.t = Bool; return true; }
if (*p.p == '"') return jstring(p, v.s), v.t = Str, true;
if (*p.p == '[') {
p.p++;
v = Val();
v.t = Arr;
p.ws();
if (*p.p == ']') { p.p++; return true; }
while (true) {
Val item;
if (!jvalue(p, item)) return false;
v.items.push_back(std::move(item));
p.ws();
if (*p.p == ',') { p.p++; continue; }
if (*p.p == ']') { p.p++; return true; }
return false;
}
}
if (*p.p == '{') {
p.p++;
v = Val();
v.t = Obj;
p.ws();
if (*p.p == '}') { p.p++; return true; }
while (true) {
p.ws();
std::string key;
if (!jstring(p, key)) return false;
p.ws();
if (*p.p != ':') return false;
p.p++;
Val val;
if (!jvalue(p, val)) return false;
v.pairs.emplace_back(std::move(key), std::move(val));
p.ws();
if (*p.p == ',') { p.p++; continue; }
if (*p.p == '}') { p.p++; return true; }
return false;
}
}
// number: JSON grammar scan then strtod
const char *start = p.p;
if (*p.p == '-' || *p.p == '+') p.p++;
if (!(*p.p >= '0' && *p.p <= '9')) return false;
while (*p.p >= '0' && *p.p <= '9') p.p++;
if (*p.p == '.') { p.p++; if (!(*p.p >= '0' && *p.p <= '9')) return false; while (*p.p >= '0' && *p.p <= '9') p.p++; }
if (*p.p == 'e' || *p.p == 'E') {
p.p++;
if (*p.p == '-' || *p.p == '+') p.p++;
if (!(*p.p >= '0' && *p.p <= '9')) return false;
while (*p.p >= '0' && *p.p <= '9') p.p++;
}
std::string buf(start, p.p);
v = Val();
v.t = Num;
v.num = strtod(buf.c_str(), NULL);
return true;
}
// ---- JS-flavoured helpers ---------------------------------------------------
static bool is_int(double v) { return v == std::floor(v) && v == v; } // Number.isInteger
static const char *kind_of(const Val &v) {
switch (v.t) {
case Null: return "null";
case Bool: return "boolean";
case Num: return is_int(v.num) ? "integer" : "number";
case Str: return "string";
case Arr: return "array";
default: return "object";
}
}
static bool deep_equal(const Val &a, const Val &b) {
if (strcmp(kind_of(a), kind_of(b)) != 0) return false;
switch (a.t) {
case Null: return true;
case Bool: return a.b == b.b;
case Num: return a.num == b.num;
case Str: return a.s == b.s;
case Arr:
if (a.items.size() != b.items.size()) return false;
for (size_t i = 0; i < a.items.size(); i++) if (!deep_equal(a.items[i], b.items[i])) return false;
return true;
default:
if (a.pairs.size() != b.pairs.size()) return false;
for (const auto &kv : a.pairs) {
const Val *other = nullptr;
for (const auto &okv : b.pairs) if (okv.first == kv.first) { other = &okv.second; break; }
if (!other || !deep_equal(kv.second, *other)) return false;
}
return true;
}
}
// JS Number-to-string: plain integers below 1e21, exponential only past the
// JS thresholds (decimal exponent < -6 or >= 21), minimal exponent digits.
static std::string js_num(double v) {
char buf[64];
if (v == 0) return "0"; // covers -0
int neg = v < 0;
double a = neg ? -v : v;
if (a == std::floor(a) && a < 1e21) {
snprintf(buf, sizeof buf, "%s%.0f", neg ? "-" : "", a);
return buf;
}
int prec;
for (prec = 15; prec <= 17; prec++) {
snprintf(buf, sizeof buf, "%.*g", prec, a);
if (strtod(buf, NULL) == a) break;
}
std::string text = buf, mant;
int eexp = 0;
size_t e = text.find_first_of("eE");
if (e != std::string::npos) { eexp = atoi(text.c_str() + e + 1); mant = text.substr(0, e); }
else mant = text;
size_t dot = mant.find('.');
std::string intpart = dot == std::string::npos ? mant : mant.substr(0, dot);
std::string digits = intpart + (dot == std::string::npos ? "" : mant.substr(dot + 1));
long exp = (long)intpart.size() - 1 + eexp;
size_t dstart = 0;
while (dstart + 1 < digits.size() && digits[dstart] == '0') { dstart++; exp--; }
std::string d = digits.substr(dstart);
std::string sign = neg ? "-" : "";
char head[64] = "", tail[64] = "", zeros[40] = "";
if (exp < -6 || exp >= 21) {
std::string rest = d.size() > 1 ? "." + d.substr(1) : "";
return sign + d.substr(0, 1) + rest + "e" + (exp >= 0 ? "+" : "") + std::to_string(exp);
}
if (exp < 0) {
for (long i = 0; i < -exp - 1; i++) strcat(zeros, "0");
return sign + "0." + zeros + d;
}
if ((long)d.size() > exp + 1) {
memcpy(head, d.c_str(), (size_t)(exp + 1));
strcpy(tail, d.c_str() + exp + 1);
return sign + head + "." + tail;
}
for (long i = 0; i < exp + 1 - (long)d.size(); i++) strcat(zeros, "0");
return sign + d + zeros;
}
// TS .length: UTF-16 code units — astral chars (4-byte UTF-8) count as 2.
static size_t utf16_len(const std::string &s) {
size_t n = 0;
for (unsigned char c : s) n += (c & 0xF8) == 0xF0 ? 2 : ((c & 0xC0) == 0x80 ? 0 : 1);
return n;
}
// JS String(v) for schema type entries and required keys.
static std::string js_str(const Val &v) {
switch (v.t) {
case Null: return "null";
case Bool: return v.b ? "true" : "false";
case Num: return js_num(v.num);
case Str: return v.s;
case Arr: {
std::string out;
for (size_t i = 0; i < v.items.size(); i++) { if (i) out += ","; out += js_str(v.items[i]); }
return out;
}
default: return "[object Object]";
}
}
// ---- validator ---------------------------------------------------------------
static const Val *obj_get(const Val &o, const std::string &key) {
for (const auto &kv : o.pairs) if (kv.first == key) return &kv.second;
return nullptr;
}
static void validate(const Val &v, const Val &schema, const std::string &path, Result &r) {
if (schema.t == Bool) {
if (!schema.b) r.issues.push_back({path, "no value is allowed here (schema is false)"});
return;
}
if (schema.t != Obj) {
r.issues.push_back({path, "invalid schema node: expected an object or boolean"});
return;
}
auto push = [&](const std::string &p, const std::string &m) { r.issues.push_back({p, m}); };
if (const Val *type = obj_get(schema, "type")) {
std::vector<std::string> allowed;
if (type->t == Arr) for (const Val &e : type->items) allowed.push_back(js_str(e));
else allowed.push_back(js_str(*type));
std::string joined;
for (size_t i = 0; i < allowed.size(); i++) { if (i) joined += "|"; joined += allowed[i]; }
const char *actual = kind_of(v);
bool ok = false;
for (const auto &t : allowed)
if (t == actual || (t == "number" && !strcmp(actual, "integer"))) ok = true;
if (!ok) push(path, "expected type " + joined + ", got " + actual);
}
if (const Val *en = obj_get(schema, "enum")) {
size_t count = en->t == Arr ? en->items.size() : 0;
bool found = false;
for (size_t i = 0; i < count; i++) if (deep_equal(v, en->items[i])) { found = true; break; }
if (!found) push(path, "value not in enum (" + std::to_string(count) + " allowed)");
}
if (const Val *k = obj_get(schema, "const"); k && !deep_equal(v, *k))
push(path, "value does not match const");
if (v.t == Num) {
const Val *m;
if ((m = obj_get(schema, "minimum")) && m->t == Num && v.num < m->num)
push(path, js_num(v.num) + " is less than minimum " + js_num(m->num));
if ((m = obj_get(schema, "maximum")) && m->t == Num && v.num > m->num)
push(path, js_num(v.num) + " is greater than maximum " + js_num(m->num));
if ((m = obj_get(schema, "exclusiveMinimum")) && m->t == Num && v.num <= m->num)
push(path, js_num(v.num) + " is not greater than exclusiveMinimum " + js_num(m->num));
if ((m = obj_get(schema, "exclusiveMaximum")) && m->t == Num && v.num >= m->num)
push(path, js_num(v.num) + " is not less than exclusiveMaximum " + js_num(m->num));
}
if (v.t == Str) {
size_t len = utf16_len(v.s);
const Val *m;
if ((m = obj_get(schema, "minLength")) && m->t == Num && len < (size_t)m->num)
push(path, "string length " + std::to_string(len) + " is less than minLength " + js_num(m->num));
if ((m = obj_get(schema, "maxLength")) && m->t == Num && len > (size_t)m->num)
push(path, "string length " + std::to_string(len) + " is greater than maxLength " + js_num(m->num));
if ((m = obj_get(schema, "pattern")) && m->t == Str) {
try {
if (!std::regex_search(v.s, std::regex(m->s, std::regex::ECMAScript)))
push(path, "string does not match pattern " + m->s);
} catch (const std::regex_error &) {
push(path, "invalid pattern in schema: " + m->s);
}
}
}
if (v.t == Arr) {
const Val *m;
if ((m = obj_get(schema, "minItems")) && m->t == Num && v.items.size() < (size_t)m->num)
push(path, "array length " + std::to_string(v.items.size()) + " is less than minItems " + js_num(m->num));
if ((m = obj_get(schema, "maxItems")) && m->t == Num && v.items.size() > (size_t)m->num)
push(path, "array length " + std::to_string(v.items.size()) + " is greater than maxItems " + js_num(m->num));
if ((m = obj_get(schema, "uniqueItems")) && m->t == Bool && m->b)
for (size_t i = 0; i < v.items.size(); i++)
for (size_t j = i + 1; j < v.items.size(); j++)
if (deep_equal(v.items[i], v.items[j]))
push(path + "[" + std::to_string(j) + "]", "duplicate item (same as index " + std::to_string(i) + ")");
if (const Val *items = obj_get(schema, "items"))
for (size_t i = 0; i < v.items.size(); i++)
validate(v.items[i], *items, path + "[" + std::to_string(i) + "]", r);
}
if (v.t == Obj) {
if (const Val *req = obj_get(schema, "required"); req && req->t == Arr)
for (const Val &rk : req->items) {
std::string key = js_str(rk);
if (!obj_get(v, key)) push(path, "missing required property \"" + key + "\"");
}
const Val *props = obj_get(schema, "properties");
if (props && props->t == Obj)
for (const auto &kv : props->pairs)
if (const Val *sub = obj_get(v, kv.first))
validate(*sub, kv.second, path + "." + kv.first, r);
if (const Val *ap = obj_get(schema, "additionalProperties"); ap && ap->t == Bool && !ap->b)
for (const auto &kv : v.pairs)
if (!(props && props->t == Obj && obj_get(*props, kv.first)))
push(path + "." + kv.first, "additional property not allowed");
}
}
static bool blank(const char *s) { while (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r') s++; return !*s; }
/** Validate a JSON document against a schema. `error` is empty when the
* verdict is real (TS: error: null). */
static Result validate_json_schema(const std::string &schema_raw, const std::string &instance_raw) {
Result r;
if (blank(schema_raw.c_str()) || blank(instance_raw.c_str())) {
r.error = "Both a schema and an instance are required";
return r;
}
P ps{schema_raw.c_str()};
Val schema;
bool ok = jvalue(ps, schema);
ps.ws();
if (!ok || *ps.p) {
r.error = "Schema: Invalid JSON";
return r;
}
P pi{instance_raw.c_str()};
Val instance;
ok = jvalue(pi, instance);
pi.ws();
if (!ok || *pi.p) {
r.error = "Instance: Invalid JSON";
return r;
}
validate(instance, schema, "$", r);
r.valid = r.issues.empty();
return 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"
} // namespace jsv
#ifdef JSV_DEMO
int main() {
auto r = jsv::validate_json_schema(
R"({"type":"object","required":["port"],"properties":{"port":{"type":"integer","minimum":1024}}})",
R"({"port":80})");
printf("valid=%d issues=%zu error=%s\n", r.valid, r.issues.size(), r.error.empty() ? "null" : r.error.c_str());
for (auto &i : r.issues) printf(" %s: %s\n", i.path.c_str(), i.message.c_str());
}
#endif
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 →