JSON Schema Validator — Go 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 Go implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Package jsonschemavalidator is the Go twin of CosmoDev's
// src/lib/json-schema-validator.ts (dual source: the web lib is TypeScript,
// the CLI lib is Go — kept in lock-step). Pure + deterministic, never panics.
// The tests in json-schema-validator_test.go share vectors with
// src/lib/json-schema-validator.test.ts so the two implementations are held
// to the same contract.
//
// It validates a JSON instance against a draft-07 SUBSET schema. Supported
// keywords: type (string or array, with the JS "integer is a number"
// allowance), enum, const, minimum, maximum, exclusiveMinimum,
// exclusiveMaximum, minLength, maxLength, pattern, minItems, maxItems,
// uniqueItems, items, required, properties, additionalProperties: false, and
// the boolean schemas true/false. Everything else ($ref/$defs, oneOf/anyOf/
// allOf/not, patternProperties, dependencies, format enforcement,
// propertyNames, contains) is ignored, exactly like the TS lib; the
// companion generator (json-to-schema) never emits any of it, so the pair
// stays coherent.
//
// Engine notes — each is a deliberate mirror of TS behavior:
//
// - JS object keys iterate in insertion order (Object.keys), which decides
// the ORDER of issues across properties and for additionalProperties.
// encoding/json's map-based decode would lose that order, so this twin
// parses with a json.Decoder Token() stream into an ordered JsonObject.
// - JS numbers are IEEE doubles: JSON has no int type, so 8080.0 is an
// "integer" (Number.isInteger), and every number printed into a message
// goes through jsNum, which reproduces the Number-to-string rules.
// - Patterns run through Go's RE2 (regexp). The regex subset the companion
// generator emits compiles identically in both engines; a pattern that
// is valid JavaScript RegExp but not RE2 (backreferences, lookarounds)
// surfaces here as the "invalid pattern in schema" issue where the TS
// lib would happily match with it.
// - TS strings measure length in UTF-16 code units, so minLength/maxLength
// count astral characters as 2 (utf16Length), and String(v) coercions
// for type/required entries go through jsString.
// - The TS catch-clause fallback for JSON.parse throwing a non-Error
// ("Invalid JSON") maps to errorMessage(nil); Go's decoder only ever
// produces error values, so that branch is exercised by the tests
// directly rather than through ValidateJsonSchema.
package jsonschemavalidator
import (
"encoding/json"
"errors"
"fmt"
"io"
"math"
"regexp"
"strconv"
"strings"
)
// ValidationIssue mirrors the TS ValidationIssue interface: path is the
// "$"-rooted path of the offending value.
type ValidationIssue struct {
Path string
Message string
}
// JsonSchemaValidateResult mirrors the TS JsonSchemaValidateResult union:
// either a verdict with a null error (Error nil) or an empty verdict with a
// string error. Error is a *string so nil stands in for the TS null.
type JsonSchemaValidateResult struct {
Valid bool
Issues []ValidationIssue
Error *string // nil when the verdict is real (TS: error: null)
}
// strptr builds the Error field (TS: error: "..." vs null).
func strptr(s string) *string { return &s }
// JsonObject is a JSON object that remembers key order. It is what
// encoding/json's map-based unmarshal cannot give us, and what the TS lib's
// Object.keys iteration (insertion order) depends on for issue ordering.
type JsonObject struct {
// Keys are the member keys in document order, unique (a duplicate JSON
// key keeps its first position but the last value, like JSON.parse).
Keys []string
// Vals maps each key to its value.
Vals map[string]JsonValue
}
// Get returns the value stored for key and whether the key is present. The
// presence flag is the TS undefined-vs-null distinction: {"const": null}
// must be checked, an absent const must not. Nil-receiver safe.
func (o *JsonObject) Get(key string) (JsonValue, bool) {
if o == nil {
return nil, false
}
v, ok := o.Vals[key]
return v, ok
}
// Has reports whether key is present. Nil-receiver safe.
func (o *JsonObject) Has(key string) bool {
if o == nil {
return false
}
_, ok := o.Vals[key]
return ok
}
// JsonValue is one JSON value: nil, bool, float64, string, []JsonValue, or
// *JsonObject — the decoded form of the TS Json type (numbers are IEEE
// doubles, exactly like JS).
type JsonValue any
// parseJson decodes raw into a JsonValue, preserving object key order, and
// rejects trailing data after the top-level value, matching JSON.parse.
// Numeric overflow does NOT fail (JS JSON.parse: 1e999 → Infinity); the
// strconv range-error value (±Inf) is accepted instead.
func parseJson(raw string) (JsonValue, error) {
dec := json.NewDecoder(strings.NewReader(raw))
dec.UseNumber() // keep the literal, then convert with Number semantics
v, err := decodeValue(dec)
if err != nil {
return nil, err
}
// JSON.parse rejects anything after the top-level value.
if _, err := dec.Token(); err == io.EOF {
return v, nil
} else if err != nil {
return nil, err
}
return nil, errors.New("unexpected data after top-level value")
}
// decodeValue reads the next token and decodes the full value that starts
// with it, building ordered objects and float64 numbers.
func decodeValue(dec *json.Decoder) (JsonValue, error) {
tok, err := dec.Token()
if err != nil {
return nil, err
}
switch t := tok.(type) {
case json.Delim:
switch t {
case '{':
obj := &JsonObject{Vals: map[string]JsonValue{}}
for dec.More() {
keyTok, err := dec.Token()
if err != nil {
return nil, err
}
key, ok := keyTok.(string)
if !ok {
return nil, fmt.Errorf("json: unexpected non-string object key %v", keyTok)
}
val, err := decodeValue(dec)
if err != nil {
return nil, err
}
// JSON.parse: a duplicate key keeps its first position,
// the last value wins.
if !obj.Has(key) {
obj.Keys = append(obj.Keys, key)
}
obj.Vals[key] = val
}
if _, err := dec.Token(); err != nil { // consume '}'
return nil, err
}
return obj, nil
case '[':
arr := []JsonValue{}
for dec.More() {
val, err := decodeValue(dec)
if err != nil {
return nil, err
}
arr = append(arr, val)
}
if _, err := dec.Token(); err != nil { // consume ']'
return nil, err
}
return arr, nil
default:
return nil, fmt.Errorf("json: unexpected delimiter %v", t)
}
case json.Number:
f, err := t.Float64()
if err != nil && !errors.Is(err, strconv.ErrRange) {
return nil, err
}
// On ErrRange f is ±Inf — what JS JSON.parse yields for overflow.
return f, nil
case string:
return t, nil
case bool:
return t, nil
case nil:
return nil, nil
default:
return nil, fmt.Errorf("json: unexpected token %v", tok)
}
}
// errorMessage coerces a parse failure into the TS catch-clause form
// (e instanceof Error ? e.message : 'Invalid JSON'). Go's decoder only
// produces error values, so the fixed fallback answers a nil error.
func errorMessage(e error) string {
if e == nil {
return "Invalid JSON"
}
return e.Error()
}
// kindOf names the JSON kind of v, mirroring kindOf() in the TS lib: an
// integral double is an "integer" (Number.isInteger), arrays are their own
// kind, null is its own kind.
func kindOf(v JsonValue) string {
switch t := v.(type) {
case nil:
return "null"
case bool:
return "boolean"
case float64:
if t == math.Trunc(t) {
return "integer"
}
return "number"
case string:
return "string"
case []JsonValue:
return "array"
case *JsonObject:
return "object"
default:
return "string" // unreachable for parsed JSON — mirrors the TS fallthrough
}
}
// jsonDeepEqual compares two JSON values structurally, mirroring deepEqual()
// in the TS lib (kind-sensitive, element/entry-wise).
func jsonDeepEqual(a, b JsonValue) bool {
switch av := a.(type) {
case nil:
return b == nil
case bool:
bv, ok := b.(bool)
return ok && av == bv
case float64:
bv, ok := b.(float64)
return ok && av == bv
case string:
bv, ok := b.(string)
return ok && av == bv
case []JsonValue:
bv, ok := b.([]JsonValue)
if !ok || len(av) != len(bv) {
return false
}
for i := range av {
if !jsonDeepEqual(av[i], bv[i]) {
return false
}
}
return true
case *JsonObject:
bv, ok := b.(*JsonObject)
if !ok || len(av.Keys) != len(bv.Keys) {
return false
}
for k, val := range av.Vals {
ov, present := bv.Get(k)
if !present || !jsonDeepEqual(val, ov) {
return false
}
}
return true
default:
return false
}
}
// jsNum renders a float64 the way JavaScript's Number-to-string does, for
// the numbers this validator prints into messages: integers below 1e21 in
// plain form ("70000", "0" — also for -0), exponential only past the JS
// thresholds (decimal exponent < -6 or >= 21), with minimal exponent digits
// ("1.5e-7", "1.2e+21").
func jsNum(v float64) string {
if v != v { // NaN — unreachable via JSON, kept for totality
return "NaN"
}
if math.IsInf(v, 0) {
if v > 0 {
return "Infinity"
}
return "-Infinity"
}
if v == 0 {
return "0" // JS prints -0 as "0"
}
if v == math.Trunc(v) && math.Abs(v) < 1e21 {
return strconv.FormatFloat(v, 'f', -1, 64)
}
// Shortest round-trip digits, harvested from the 'e' form: d.ddde±dd.
e := strconv.FormatFloat(v, 'e', -1, 64)
sign := ""
if v < 0 {
sign = "-"
e = e[1:]
}
mant, expPart, _ := strings.Cut(e, "e")
exp, _ := strconv.Atoi(expPart)
negExp := exp < 0
if negExp {
exp = -exp
}
digits := strings.Replace(mant, ".", "", 1)
if negExp && exp > 6 || !negExp && exp >= 21 {
out := digits[:1]
if len(digits) > 1 {
out += "." + digits[1:]
}
es := strconv.Itoa(exp)
if negExp {
es = "-" + es
} else {
es = "+" + es
}
return sign + out + "e" + es
}
if negExp {
return sign + "0." + strings.Repeat("0", exp-1) + digits
}
intLen := exp + 1
if intLen >= len(digits) {
return sign + digits + strings.Repeat("0", intLen-len(digits))
}
return sign + digits[:intLen] + "." + digits[intLen:]
}
// jsString mirrors JS String(v) for the coercions the TS lib applies to
// schema type entries and required keys.
func jsString(v JsonValue) string {
switch t := v.(type) {
case nil:
return "null"
case string:
return t
case bool:
if t {
return "true"
}
return "false"
case float64:
return jsNum(t)
case []JsonValue:
parts := make([]string, len(t))
for i, x := range t {
parts[i] = jsString(x)
}
return strings.Join(parts, ",")
default:
return "[object Object]"
}
}
// utf16Length counts UTF-16 code units — the TS v.length for strings: one
// unit per BMP rune, two per astral (surrogate pair).
func utf16Length(s string) int {
n := 0
for _, r := range s {
n++
if r > 0xFFFF {
n++
}
}
return n
}
// addIssue appends one issue; out is the shared accumulator the TS closure
// captures.
func addIssue(out *[]ValidationIssue, path, message string) {
*out = append(*out, ValidationIssue{Path: path, Message: message})
}
// validate checks one value against one schema node, appending issues with
// paths. It mirrors validate() in the TS lib block for block — including the
// order issues are produced in (type, enum, const, numeric bounds, string
// rules, array rules with uniqueItems before items, object rules with
// required before properties before additionalProperties).
func validate(v JsonValue, schema JsonValue, path string, out *[]ValidationIssue) {
if b, ok := schema.(bool); ok {
if b {
return
}
addIssue(out, path, "no value is allowed here (schema is false)")
return
}
s, ok := schema.(*JsonObject)
if !ok {
// schema is null, a non-object, or an array.
addIssue(out, path, "invalid schema node: expected an object or boolean")
return
}
// type
if tv, has := s.Get("type"); has {
var allowed []string
if tvArr, isArr := tv.([]JsonValue); isArr {
for _, x := range tvArr {
allowed = append(allowed, jsString(x))
}
} else {
allowed = []string{jsString(tv)}
}
actual := kindOf(v)
typeOk := false
for _, t := range allowed {
if t == actual || (t == "number" && actual == "integer") {
typeOk = true
break
}
}
if !typeOk {
addIssue(out, path, "expected type "+strings.Join(allowed, "|")+", got "+actual)
}
}
// enum
if ev, has := s.Get("enum"); has {
list, _ := ev.([]JsonValue)
found := false
for _, e := range list {
if jsonDeepEqual(v, e) {
found = true
break
}
}
if !found {
addIssue(out, path, "value not in enum ("+strconv.Itoa(len(list))+" allowed)")
}
}
// const
if cv, has := s.Get("const"); has && !jsonDeepEqual(v, cv) {
addIssue(out, path, "value does not match const")
}
// numeric bounds
if num, isNum := v.(float64); isNum {
if m, has := s.Get("minimum"); has {
if f, isF := m.(float64); isF && num < f {
addIssue(out, path, jsNum(num)+" is less than minimum "+jsNum(f))
}
}
if m, has := s.Get("maximum"); has {
if f, isF := m.(float64); isF && num > f {
addIssue(out, path, jsNum(num)+" is greater than maximum "+jsNum(f))
}
}
if m, has := s.Get("exclusiveMinimum"); has {
if f, isF := m.(float64); isF && num <= f {
addIssue(out, path, jsNum(num)+" is not greater than exclusiveMinimum "+jsNum(f))
}
}
if m, has := s.Get("exclusiveMaximum"); has {
if f, isF := m.(float64); isF && num >= f {
addIssue(out, path, jsNum(num)+" is not less than exclusiveMaximum "+jsNum(f))
}
}
}
// string rules
if str, isStr := v.(string); isStr {
if m, has := s.Get("minLength"); has {
if f, isF := m.(float64); isF && float64(utf16Length(str)) < f {
addIssue(out, path, "string length "+strconv.Itoa(utf16Length(str))+
" is less than minLength "+jsNum(f))
}
}
if m, has := s.Get("maxLength"); has {
if f, isF := m.(float64); isF && float64(utf16Length(str)) > f {
addIssue(out, path, "string length "+strconv.Itoa(utf16Length(str))+
" is greater than maxLength "+jsNum(f))
}
}
if p, has := s.Get("pattern"); has {
if ps, isS := p.(string); isS {
re, err := regexp.Compile(ps)
if err != nil {
addIssue(out, path, "invalid pattern in schema: "+ps)
} else if !re.MatchString(str) {
addIssue(out, path, "string does not match pattern "+ps)
}
}
}
}
// array rules
if arr, isArr := v.([]JsonValue); isArr {
if m, has := s.Get("minItems"); has {
if f, isF := m.(float64); isF && float64(len(arr)) < f {
addIssue(out, path, "array length "+strconv.Itoa(len(arr))+
" is less than minItems "+jsNum(f))
}
}
if m, has := s.Get("maxItems"); has {
if f, isF := m.(float64); isF && float64(len(arr)) > f {
addIssue(out, path, "array length "+strconv.Itoa(len(arr))+
" is greater than maxItems "+jsNum(f))
}
}
if uv, has := s.Get("uniqueItems"); has {
if ub, isB := uv.(bool); isB && ub {
for i := 0; i < len(arr); i++ {
for j := i + 1; j < len(arr); j++ {
if jsonDeepEqual(arr[i], arr[j]) {
addIssue(out, path+"["+strconv.Itoa(j)+"]",
"duplicate item (same as index "+strconv.Itoa(i)+")")
}
}
}
}
}
if items, has := s.Get("items"); has {
for i, item := range arr {
validate(item, items, path+"["+strconv.Itoa(i)+"]", out)
}
}
}
// object rules
if obj, isObj := v.(*JsonObject); isObj {
if rv, has := s.Get("required"); has {
if reqArr, isArr := rv.([]JsonValue); isArr {
for _, rk := range reqArr {
key := jsString(rk)
if !obj.Has(key) {
addIssue(out, path, `missing required property "`+key+`"`)
}
}
}
}
// (s.properties ?? {}): absent, null, or non-object → no properties.
var props *JsonObject
if pv, has := s.Get("properties"); has {
if po, isObj := pv.(*JsonObject); isObj {
props = po
}
}
if props != nil {
for _, key := range props.Keys {
if val, present := obj.Get(key); present {
validate(val, props.Vals[key], path+"."+key, out)
}
}
}
if apv, has := s.Get("additionalProperties"); has {
if ab, isB := apv.(bool); isB && !ab {
known := map[string]bool{}
if props != nil {
for _, k := range props.Keys {
known[k] = true
}
}
for _, key := range obj.Keys {
if !known[key] {
addIssue(out, path+"."+key, "additional property not allowed")
}
}
}
}
}
}
// ValidateJsonSchema validates a JSON document (instanceRaw) against a
// schema (schemaRaw). It is the Go twin of validateJsonSchema() in
// src/lib/json-schema-validator.ts and must agree with it on every shared
// vector.
func ValidateJsonSchema(schemaRaw, instanceRaw string) JsonSchemaValidateResult {
if strings.TrimSpace(schemaRaw) == "" || strings.TrimSpace(instanceRaw) == "" {
return JsonSchemaValidateResult{
Valid: false,
Issues: []ValidationIssue{},
Error: strptr("Both a schema and an instance are required"),
}
}
schema, err := parseJson(schemaRaw)
if err != nil {
return JsonSchemaValidateResult{
Valid: false,
Issues: []ValidationIssue{},
Error: strptr("Schema: " + errorMessage(err)),
}
}
instance, err := parseJson(instanceRaw)
if err != nil {
return JsonSchemaValidateResult{
Valid: false,
Issues: []ValidationIssue{},
Error: strptr("Instance: " + errorMessage(err)),
}
}
issues := []ValidationIssue{}
validate(instance, schema, "$", &issues)
if len(issues) == 0 {
return JsonSchemaValidateResult{Valid: true, Issues: []ValidationIssue{}, Error: nil}
}
return JsonSchemaValidateResult{Valid: false, Issues: issues, Error: nil}
}
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 →