JSON Schema Validator — Python 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 Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
"""json-schema-validator — draft-07 SUBSET JSON Schema validator. Python 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 companion generator (json-to-schema) never emits any of them.
Numbers print into messages with JS Number-to-string rules (70000, 1.5e-7,
1e+21). Dict iteration order (insertion) drives issue ordering. Never
raises — errors travel in the result dict.
"""
import json
import math
import re
def _is_integral(v):
"""Number.isInteger: finite and equal to its floor (ints always are)."""
if isinstance(v, int):
return True
return math.isfinite(v) and v == math.floor(v)
def kind_of(v):
"""Seven JSON kinds; bool checked before int (bool subclasses int)."""
if isinstance(v, bool):
return "boolean"
if v is None:
return "null"
if isinstance(v, (int, float)):
return "integer" if _is_integral(v) else "number"
if isinstance(v, list):
return "array"
if isinstance(v, dict):
return "object"
return "string"
def _is_num(x):
"""The TS typeof x === 'number' guard (bool is not a number here)."""
return isinstance(x, (int, float)) and not isinstance(x, bool)
def deep_equal(a, b):
"""Kind-sensitive structural equality; objects compare by key sets."""
if isinstance(a, bool) != isinstance(b, bool):
return False
if kind_of(a) != kind_of(b):
return False
if isinstance(a, list):
return len(a) == len(b) and all(deep_equal(x, y) for x, y in zip(a, b))
if isinstance(a, dict):
return len(a) == len(b) and all(k in b and deep_equal(a[k], b[k]) for k in a)
return a == b
def js_num(v):
"""JS Number-to-string: plain integers below 1e21, exponential only past
the JS thresholds (decimal exponent < -6 or >= 21), minimal exponent
digits ('1.5e-7', '1e+21')."""
if v == 0:
return "0"
neg = v < 0
a = -v if neg else v
if _is_integral(a) and (isinstance(a, int) or a < 1e21):
return ("-" if neg else "") + str(int(a))
text = repr(a)
if "e" in text or "E" in text:
mant, _, e = text.replace("E", "e").partition("e")
exp = int(e)
digits = mant.replace(".", "")
else:
intpart, _, frac = text.partition(".")
digits = intpart + frac
exp = len(intpart) - 1
while digits.startswith("0") and len(digits) > 1:
digits = digits[1:]
exp -= 1
if exp < -6 or exp >= 21:
head = digits[0] + (("." + digits[1:]) if len(digits) > 1 else "")
return ("-" if neg else "") + head + "e" + ("+" if exp >= 0 else "-") + str(abs(exp))
if exp < 0:
return ("-" if neg else "") + "0." + "0" * (-exp - 1) + digits
if len(digits) > exp + 1:
return ("-" if neg else "") + digits[:exp + 1] + "." + digits[exp + 1:]
return ("-" if neg else "") + digits + "0" * (exp + 1 - len(digits))
def utf16_len(s):
"""TS .length: UTF-16 code units — astral chars count as 2."""
return sum(2 if ord(c) > 0xFFFF else 1 for c in s)
def js_str(v):
"""JS String(v) for schema type entries and required keys."""
if v is None:
return "null"
if isinstance(v, bool):
return "true" if v else "false"
if isinstance(v, (int, float)):
return js_num(v)
if isinstance(v, str):
return v
if isinstance(v, list):
return ",".join(js_str(x) for x in v)
return "[object Object]"
def _issue(out, path, message):
out.append({"path": path, "message": message})
def _validate(v, schema, path, out):
if schema is True:
return
if schema is False:
_issue(out, path, "no value is allowed here (schema is false)")
return
if not isinstance(schema, dict):
_issue(out, path, "invalid schema node: expected an object or boolean")
return
if "type" in schema:
t = schema["type"]
allowed = [js_str(x) for x in t] if isinstance(t, list) else [js_str(t)]
actual = kind_of(v)
if not any(t == actual or (t == "number" and actual == "integer") for t in allowed):
_issue(out, path, "expected type " + "|".join(allowed) + ", got " + actual)
if "enum" in schema:
entries = schema["enum"] if isinstance(schema["enum"], list) else []
if not any(deep_equal(v, e) for e in entries):
_issue(out, path, "value not in enum (%d allowed)" % len(entries))
if "const" in schema and not deep_equal(v, schema["const"]):
_issue(out, path, "value does not match const")
if _is_num(v):
m = schema.get("minimum")
if _is_num(m) and v < m:
_issue(out, path, js_num(v) + " is less than minimum " + js_num(m))
m = schema.get("maximum")
if _is_num(m) and v > m:
_issue(out, path, js_num(v) + " is greater than maximum " + js_num(m))
m = schema.get("exclusiveMinimum")
if _is_num(m) and v <= m:
_issue(out, path, js_num(v) + " is not greater than exclusiveMinimum " + js_num(m))
m = schema.get("exclusiveMaximum")
if _is_num(m) and v >= m:
_issue(out, path, js_num(v) + " is not less than exclusiveMaximum " + js_num(m))
if isinstance(v, str):
n = utf16_len(v)
m = schema.get("minLength")
if _is_num(m) and n < m:
_issue(out, path, "string length %d is less than minLength %s" % (n, js_num(m)))
m = schema.get("maxLength")
if _is_num(m) and n > m:
_issue(out, path, "string length %d is greater than maxLength %s" % (n, js_num(m)))
p = schema.get("pattern")
if isinstance(p, str):
try:
ok = re.search(p, v) is not None
except re.error:
ok = None
if ok is None:
_issue(out, path, "invalid pattern in schema: " + p)
elif not ok:
_issue(out, path, "string does not match pattern " + p)
if isinstance(v, list):
m = schema.get("minItems")
if _is_num(m) and len(v) < m:
_issue(out, path, "array length %d is less than minItems %s" % (len(v), js_num(m)))
m = schema.get("maxItems")
if _is_num(m) and len(v) > m:
_issue(out, path, "array length %d is greater than maxItems %s" % (len(v), js_num(m)))
if schema.get("uniqueItems") is True:
for i in range(len(v)):
for j in range(i + 1, len(v)):
if deep_equal(v[i], v[j]):
_issue(out, path + "[%d]" % j, "duplicate item (same as index %d)" % i)
if "items" in schema:
for i, item in enumerate(v):
_validate(item, schema["items"], path + "[%d]" % i, out)
if isinstance(v, dict):
req = schema.get("required")
if isinstance(req, list):
for rk in req:
key = js_str(rk)
if key not in v:
_issue(out, path, 'missing required property "%s"' % key)
props = schema.get("properties")
if not isinstance(props, dict):
props = {}
for key, sub in props.items():
if key in v:
_validate(v[key], sub, path + "." + key, out)
if schema.get("additionalProperties") is False:
for key in v:
if key not in props:
_issue(out, path + "." + key, "additional property not allowed")
def validate_json_schema(schema_raw, instance_raw):
"""Validate a JSON document against a schema. Returns
{valid, issues: [{path, message}], error} — error is None when the
verdict is real (TS: error: null)."""
if not schema_raw.strip() or not instance_raw.strip():
return {"valid": False, "issues": [], "error": "Both a schema and an instance are required"}
try:
schema = json.loads(schema_raw)
except ValueError as e:
return {"valid": False, "issues": [], "error": "Schema: " + (str(e) or "Invalid JSON")}
try:
instance = json.loads(instance_raw)
except ValueError as e:
return {"valid": False, "issues": [], "error": "Instance: " + (str(e) or "Invalid JSON")}
issues = []
_validate(instance, schema, "$", issues)
if issues:
return {"valid": False, "issues": issues, "error": None}
return {"valid": True, "issues": [], "error": None}
# Example:
# validate_json_schema(
# '{"type":"object","required":["port"],"properties":{"port":{"type":"integer","minimum":1024}}}',
# '{"port":80}')["issues"]
# → [{"path": "$.port", "message": "80 is less than minimum 1024"}]
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 →