JSON Schema Validator — Swift 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 Swift implementation — the same logic the interactive tool runs, in a shareable, citable form.
// json-schema-validator — draft-07 SUBSET JSON Schema validator. Swift 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. Foundation's JSONSerialization gives no
// key-order guarantee, so this file carries a terse byte-level recursive-
// descent parser whose tuple arrays keep insertion order (issue ordering
// then matches the TS Object.keys walk); patterns run through
// NSRegularExpression (ICU, close to JS RegExp). Numbers print into messages
// with JS Number-to-string rules via jsNum (70000, 1.5e-7, 1e+21). Never
// traps — errors travel in the result struct.
import Foundation
indirect enum JVal {
case nul
case bool(Bool)
case num(Double)
case str(String)
case arr([JVal])
case obj([(String, JVal)]) // tuple array keeps insertion order
}
struct Issue { let path: String; let message: String }
struct Result {
var valid = false
var issues: [Issue] = []
var error: String? // nil when the verdict is real (TS: error: null)
}
// ---- JSON parser (byte-level recursive descent) ------------------------------
struct P {
let bytes: [UInt8]
var i = 0
mutating func ws() { while i < bytes.count && (bytes[i] == 32 || bytes[i] == 9 || bytes[i] == 10 || bytes[i] == 13) { i += 1 } }
}
private func hex4(_ p: inout P) -> UInt32? {
var v: UInt32 = 0
for _ in 0..<4 {
guard p.i < p.bytes.count else { return nil }
let c = p.bytes[p.i]
let d: UInt32
switch c {
case 0x30...0x39: d = UInt32(c - 0x30)
case 0x61...0x66: d = UInt32(c - 0x61 + 10)
case 0x41...0x46: d = UInt32(c - 0x41 + 10)
default: return nil
}
v = v << 4 | d
p.i += 1
}
return v
}
private func utf8Enc(_ cp: UInt32) -> [UInt8] {
if cp < 0x80 { return [UInt8(cp)] }
if cp < 0x800 { return [UInt8(0xC0 | (cp >> 6)), UInt8(0x80 | (cp & 63))] }
if cp < 0x10000 { return [UInt8(0xE0 | (cp >> 12)), UInt8(0x80 | ((cp >> 6) & 63)), UInt8(0x80 | (cp & 63))] }
return [UInt8(0xF0 | (cp >> 18)), UInt8(0x80 | ((cp >> 12) & 63)), UInt8(0x80 | ((cp >> 6) & 63)), UInt8(0x80 | (cp & 63))]
}
private func jstring(_ p: inout P) -> String? {
guard p.bytes[p.i] == UInt8(ascii: "\"") else { return nil }
p.i += 1
var out: [UInt8] = []
while true {
guard p.i < p.bytes.count else { return nil }
let b = p.bytes[p.i]
if b == UInt8(ascii: "\"") { p.i += 1; return String(decoding: out, as: UTF8.self) }
if b == UInt8(ascii: "\\") {
p.i += 1
guard p.i < p.bytes.count else { return nil }
switch p.bytes[p.i] {
case UInt8(ascii: "\""): out.append(UInt8(ascii: "\""))
case UInt8(ascii: "\\"): out.append(UInt8(ascii: "\\"))
case UInt8(ascii: "/"): out.append(UInt8(ascii: "/"))
case UInt8(ascii: "b"): out.append(8)
case UInt8(ascii: "f"): out.append(12)
case UInt8(ascii: "n"): out.append(10)
case UInt8(ascii: "r"): out.append(13)
case UInt8(ascii: "t"): out.append(9)
case UInt8(ascii: "u"):
p.i += 1
guard var cp = hex4(&p) else { return nil }
if cp >= 0xD800 && cp <= 0xDBFF && p.i + 1 < p.bytes.count
&& p.bytes[p.i + 1] == UInt8(ascii: "\\") && p.bytes[p.i + 2] == UInt8(ascii: "u") {
let save = p.i
p.i += 2
if let lo = hex4(&p), lo >= 0xDC00, lo <= 0xDFFF {
cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00)
} else { p.i = save; cp = 0xFFFD }
} else if cp >= 0xD800 && cp <= 0xDFFF { cp = 0xFFFD }
out.append(contentsOf: utf8Enc(cp))
continue
default: return nil
}
p.i += 1
} else if b < 0x20 { return nil }
else { out.append(b); p.i += 1 }
}
}
private func jvalue(_ p: inout P) -> JVal? {
p.ws()
guard p.i < p.bytes.count else { return nil }
let b = p.bytes[p.i]
if b == UInt8(ascii: "n") {
guard p.i + 4 <= p.bytes.count, p.bytes[p.i..<p.i+4].elementsEqual("null".utf8) else { return nil }
p.i += 4; return .nul
}
if b == UInt8(ascii: "t") {
guard p.i + 4 <= p.bytes.count, p.bytes[p.i..<p.i+4].elementsEqual("true".utf8) else { return nil }
p.i += 4; return .bool(true)
}
if b == UInt8(ascii: "f") {
guard p.i + 5 <= p.bytes.count, p.bytes[p.i..<p.i+5].elementsEqual("false".utf8) else { return nil }
p.i += 5; return .bool(false)
}
if b == UInt8(ascii: "\"") {
guard let s = jstring(&p) else { return nil }
return .str(s)
}
if b == UInt8(ascii: "[") {
p.i += 1
var arr: [JVal] = []
p.ws()
if p.i < p.bytes.count, p.bytes[p.i] == UInt8(ascii: "]") { p.i += 1; return .arr(arr) }
while true {
guard let item = jvalue(&p) else { return nil }
arr.append(item)
p.ws()
guard p.i < p.bytes.count else { return nil }
if p.bytes[p.i] == UInt8(ascii: ",") { p.i += 1; continue }
if p.bytes[p.i] == UInt8(ascii: "]") { p.i += 1; return .arr(arr) }
return nil
}
}
if b == UInt8(ascii: "{") {
p.i += 1
var obj: [(String, JVal)] = []
p.ws()
if p.i < p.bytes.count, p.bytes[p.i] == UInt8(ascii: "}") { p.i += 1; return .obj(obj) }
while true {
p.ws()
guard let key = jstring(&p) else { return nil }
p.ws()
guard p.i < p.bytes.count, p.bytes[p.i] == UInt8(ascii: ":") else { return nil }
p.i += 1
guard let val = jvalue(&p) else { return nil }
obj.append((key, val))
p.ws()
guard p.i < p.bytes.count else { return nil }
if p.bytes[p.i] == UInt8(ascii: ",") { p.i += 1; continue }
if p.bytes[p.i] == UInt8(ascii: "}") { p.i += 1; return .obj(obj) }
return nil
}
}
// number: JSON grammar scan then Double(String)
let start = p.i
if b == UInt8(ascii: "-") { p.i += 1 }
guard p.i < p.bytes.count, p.bytes[p.i] >= 0x30, p.bytes[p.i] <= 0x39 else { return nil }
while p.i < p.bytes.count, p.bytes[p.i] >= 0x30, p.bytes[p.i] <= 0x39 { p.i += 1 }
if p.i < p.bytes.count, p.bytes[p.i] == UInt8(ascii: ".") {
p.i += 1
guard p.i < p.bytes.count, p.bytes[p.i] >= 0x30, p.bytes[p.i] <= 0x39 else { return nil }
while p.i < p.bytes.count, p.bytes[p.i] >= 0x30, p.bytes[p.i] <= 0x39 { p.i += 1 }
}
if p.i < p.bytes.count, p.bytes[p.i] == UInt8(ascii: "e") || p.bytes[p.i] == UInt8(ascii: "E") {
p.i += 1
if p.i < p.bytes.count, p.bytes[p.i] == UInt8(ascii: "-") || p.bytes[p.i] == UInt8(ascii: "+") { p.i += 1 }
guard p.i < p.bytes.count, p.bytes[p.i] >= 0x30, p.bytes[p.i] <= 0x39 else { return nil }
while p.i < p.bytes.count, p.bytes[p.i] >= 0x30, p.bytes[p.i] <= 0x39 { p.i += 1 }
}
guard let d = Double(String(decoding: p.bytes[start..<p.i], as: UTF8.self)) else { return nil }
return .num(d)
}
// ---- JS-flavoured helpers ------------------------------------------------------
// Number.isInteger: finite and equal to its floor.
private func isIntegral(_ v: Double) -> Bool { v == v.rounded(.down) && v.isFinite }
private func kindOf(_ v: JVal) -> String {
switch v {
case .nul: return "null"
case .bool: return "boolean"
case .num(let d): return isIntegral(d) ? "integer" : "number"
case .str: return "string"
case .arr: return "array"
case .obj: return "object"
}
}
private func deepEqual(_ a: JVal, _ b: JVal) -> Bool {
if kindOf(a) != kindOf(b) { return false }
switch (a, b) {
case (.nul, .nul): return true
case (.bool(let x), .bool(let y)): return x == y
case (.num(let x), .num(let y)): return x == y
case (.str(let x), .str(let y)): return x == y
case (.arr(let x), .arr(let y)):
return x.count == y.count && zip(x, y).allSatisfy { deepEqual($0, $1) }
case (.obj(let x), .obj(let y)):
if x.count != y.count { return false }
for (k, v) in x {
guard let (_, ov) = y.first(where: { $0.0 == k }), deepEqual(v, ov) else { return false }
}
return true
default: return false
}
}
// JS Number-to-string: plain integers below 1e21, exponential only past the
// JS thresholds (decimal exponent < -6 or >= 21), minimal exponent digits.
func jsNum(_ v: Double) -> String {
if v == 0 { return "0" } // covers -0
let neg = v < 0
let a = neg ? -v : v
if isIntegral(a) && a < 1e21 {
return (neg ? "-" : "") + String(format: "%.0f", a)
}
// Swift's shortest description, re-rendered to JS thresholds.
let s = "\(a)"
var mant = s
var eexp = 0
if let e = s.firstIndex(where: { $0 == "e" || $0 == "E" }) {
eexp = Int(s[s.index(after: e)...]) ?? 0
mant = String(s[s.startIndex..<e])
}
let dot = mant.firstIndex(of: ".")
let intpart = dot.map { String(mant[mant.startIndex..<$0]) } ?? mant
var digits = intpart + (dot.map { String(mant[mant.index(after: $0)...]) } ?? "")
var exp = intpart.count - 1 + eexp
while digits.count > 1 && digits.hasPrefix("0") { digits.removeFirst(); exp -= 1 }
var out = neg ? "-" : ""
if exp < -6 || exp >= 21 {
out += String(digits.prefix(1))
if digits.count > 1 { out += "." + String(digits.dropFirst()) }
out += "e" + (exp >= 0 ? "+" : "") + String(exp)
} else if exp < 0 {
out += "0." + String(repeating: "0", count: -exp - 1) + digits
} else if digits.count > exp + 1 {
out += digits.prefix(Int(exp + 1)) + "." + digits.dropFirst(Int(exp + 1))
} else {
out += digits + String(repeating: "0", count: Int(exp + 1) - digits.count)
}
return out
}
// TS .length: UTF-16 code units — astral chars count as 2.
private func utf16Len(_ s: String) -> Int { s.utf16.count }
// JS String(v) for schema type entries and required keys.
private func jsStr(_ v: JVal) -> String {
switch v {
case .nul: return "null"
case .bool(let b): return b ? "true" : "false"
case .num(let d): return jsNum(d)
case .str(let s): return s
case .arr(let a): return a.map(jsStr).joined(separator: ",")
case .obj: return "[object Object]"
}
}
// ---- validator -------------------------------------------------------------------
private func objGet(_ o: [(String, JVal)], _ key: String) -> JVal? {
for (k, v) in o where k == key { return v }
return nil
}
private func validate(_ v: JVal, _ schema: JVal, _ path: String, _ r: inout Result) {
if case .bool(let b) = schema {
if !b { r.issues.append(Issue(path: path, message: "no value is allowed here (schema is false)")) }
return
}
guard case .obj(let s) = schema else {
r.issues.append(Issue(path: path, message: "invalid schema node: expected an object or boolean"))
return
}
if let t = objGet(s, "type") {
let allowed: [String]
if case .arr(let entries) = t { allowed = entries.map(jsStr) } else { allowed = [jsStr(t)] }
let actual = kindOf(v)
let ok = allowed.contains { $0 == actual || ($0 == "number" && actual == "integer") }
if !ok { r.issues.append(Issue(path: path, message: "expected type \(allowed.joined(separator: "|")), got \(actual)")) }
}
if let e = objGet(s, "enum") {
let list: [JVal] = { if case .arr(let a) = e { return a } else { return [] } }()
if !list.contains(where: { deepEqual(v, $0) }) {
r.issues.append(Issue(path: path, message: "value not in enum (\(list.count) allowed)"))
}
}
if let k = objGet(s, "const"), !deepEqual(v, k) {
r.issues.append(Issue(path: path, message: "value does not match const"))
}
if case .num(let dv) = v {
for (key, msg) in [("minimum", "is less than minimum"), ("maximum", "is greater than maximum"),
("exclusiveMinimum", "is not greater than exclusiveMinimum"),
("exclusiveMaximum", "is not less than exclusiveMaximum")] {
if let m = objGet(s, key), case .num(let mv) = m {
let violated: Bool
switch key {
case "minimum": violated = dv < mv
case "maximum": violated = dv > mv
case "exclusiveMinimum": violated = dv <= mv
default: violated = dv >= mv
}
if violated { r.issues.append(Issue(path: path, message: "\(jsNum(dv)) \(msg) \(jsNum(mv))")) }
}
}
}
if case .str(let sv) = v {
let len = utf16Len(sv)
for (key, msg) in [("minLength", "is less than minLength"), ("maxLength", "is greater than maxLength")] {
if let m = objGet(s, key), case .num(let mv) = m {
let violated = key == "minLength" ? len < Int(mv) : len > Int(mv)
if violated { r.issues.append(Issue(path: path, message: "string length \(len) \(msg) \(jsNum(mv))")) }
}
}
if let p = objGet(s, "pattern"), case .str(let pat) = p {
if let re = try? NSRegularExpression(pattern: pat) {
let range = NSRange(sv.startIndex..., in: sv)
if re.firstMatch(in: sv, range: range) == nil {
r.issues.append(Issue(path: path, message: "string does not match pattern \(pat)"))
}
} else {
r.issues.append(Issue(path: path, message: "invalid pattern in schema: \(pat)"))
}
}
}
if case .arr(let av) = v {
for (key, msg) in [("minItems", "is less than minItems"), ("maxItems", "is greater than maxItems")] {
if let m = objGet(s, key), case .num(let mv) = m {
let violated = key == "minItems" ? av.count < Int(mv) : av.count > Int(mv)
if violated { r.issues.append(Issue(path: path, message: "array length \(av.count) \(msg) \(jsNum(mv))")) }
}
}
if let u = objGet(s, "uniqueItems"), case .bool(true) = u {
for i in av.indices {
for j in (i + 1)..<av.count where deepEqual(av[i], av[j]) {
r.issues.append(Issue(path: "\(path)[\(j)]", message: "duplicate item (same as index \(i))"))
}
}
}
if let items = objGet(s, "items") {
for (i, item) in av.enumerated() { validate(item, items, "\(path)[\(i)]", &r) }
}
}
if case .obj(let ov) = v {
if let rq = objGet(s, "required"), case .arr(let rl) = rq {
for rk in rl {
let key = jsStr(rk)
if objGet(ov, key) == nil {
r.issues.append(Issue(path: path, message: "missing required property \"\(key)\""))
}
}
}
if let pp = objGet(s, "properties"), case .obj(let props) = pp {
for (key, sub) in props {
if let subv = objGet(ov, key) { validate(subv, sub, "\(path).\(key)", &r) }
}
if let ap = objGet(s, "additionalProperties"), case .bool(false) = ap {
for (key, _) in ov where objGet(props, key) == nil {
r.issues.append(Issue(path: "\(path).\(key)", message: "additional property not allowed"))
}
}
}
}
}
private func blank(_ s: String) -> Bool { s.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
/** Validate a JSON document against a schema. */
func validateJsonSchema(_ schemaRaw: String, _ instanceRaw: String) -> Result {
var r = Result()
if blank(schemaRaw) || blank(instanceRaw) {
r.error = "Both a schema and an instance are required"
return r
}
var ps = P(bytes: Array(schemaRaw.utf8))
guard let schema = jvalue(&ps) else { r.error = "Schema: Invalid JSON"; return r }
ps.ws()
guard ps.i == ps.bytes.count else { r.error = "Schema: Invalid JSON"; return r }
var pi = P(bytes: Array(instanceRaw.utf8))
guard let instance = jvalue(&pi) else { r.error = "Instance: Invalid JSON"; return r }
pi.ws()
guard pi.i == pi.bytes.count else { r.error = "Instance: Invalid JSON"; return r }
validate(instance, schema, "$", &r)
r.valid = r.issues.isEmpty
return r
}
// Example:
// validateJsonSchema(
// #"{"type":"object","required":["port"],"properties":{"port":{"type":"integer","minimum":1024}}}"#,
// #"{"port":80}"#).issues[0].message
// → "80 is less than minimum 1024"
let demo = validateJsonSchema(
"{\"type\":\"object\",\"required\":[\"port\"],\"properties\":{\"port\":{\"type\":\"integer\",\"minimum\":1024}}}",
"{\"port\":80}")
print("valid=\(demo.valid) issues=\(demo.issues.count) error=\(demo.error ?? "nil")")
for i in demo.issues { print(" \(i.path): \(i.message)") }
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 →