JSON Schema Validator — Kotlin 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 Kotlin implementation — the same logic the interactive tool runs, in a shareable, citable form.
// json-schema-validator — draft-07 SUBSET JSON Schema validator. Kotlin 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 JVM ships no JSON parser, so this file
// carries a terse recursive-descent one building LinkedHashMap/ArrayList/
// String/Double/Boolean trees (LinkedHashMap keeps insertion order, so issue
// ordering matches the TS Object.keys walk); patterns run through
// java.util.regex via kotlin.text.Regex. All JSON numbers become 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). Never throws — errors travel in the Result.
import java.math.BigDecimal
import java.util.regex.PatternSyntaxException
data class Issue(val path: String, val message: String)
class Result {
var valid = false
val issues = mutableListOf<Issue>()
var error: String? = null // null when the verdict is real (TS: error: null)
}
// ---- JSON parser (recursive descent; throws IllegalArgumentException) -------
private class Parser(private val src: String) {
private var pos = 0
private fun ws() { while (pos < src.length && src[pos] in " \t\n\r") pos++ }
private fun peek(): Char { ws(); return if (pos < src.length) src[pos] else ' ' }
private fun take(c: Char): Boolean { if (peek() == c) { pos++; return true }; return false }
fun parseDocument(): Any? {
val v = parseValue()
ws()
if (pos != src.length) throw IllegalArgumentException("Invalid JSON")
return v
}
private fun parseValue(): Any? = when (val c = peek()) {
'{' -> parseObject()
'[' -> parseArray()
'"' -> parseString()
't' -> expect("true").let { true }
'f' -> expect("false").let { false }
'n' -> expect("null").let { null }
else -> if (c == '-' || c.isDigit()) parseNumber() else throw IllegalArgumentException("Invalid JSON")
}
private fun expect(word: String) {
if (!src.startsWith(word, pos)) throw IllegalArgumentException("Invalid JSON")
pos += word.length
}
private fun parseObject(): Map<String, Any?> {
pos++ // {
val m = LinkedHashMap<String, Any?>()
if (take('}')) return m
while (true) {
if (peek() != '"') throw IllegalArgumentException("Invalid JSON")
val key = parseString()
if (!take(':')) throw IllegalArgumentException("Invalid JSON")
m[key] = parseValue()
if (take(',')) continue
if (take('}')) return m
throw IllegalArgumentException("Invalid JSON")
}
}
private fun parseArray(): List<Any?> {
pos++ // [
val a = mutableListOf<Any?>()
if (take(']')) return a
while (true) {
a.add(parseValue())
if (take(',')) continue
if (take(']')) return a
throw IllegalArgumentException("Invalid JSON")
}
}
private fun parseString(): String {
pos++ // opening quote
val sb = StringBuilder()
while (true) {
if (pos >= src.length) throw IllegalArgumentException("Invalid JSON")
when (val c = src[pos++]) {
'"' -> return sb.toString()
'\\' -> when (val e = src[pos++]) {
'"' -> sb.append('"')
'\\' -> sb.append('\\')
'/' -> sb.append('/')
'b' -> sb.append('\b')
'f' -> sb.append(0x0C.toChar()) // form feed (no \f escape in Kotlin)
'n' -> sb.append('\n')
'r' -> sb.append('\r')
't' -> sb.append('\t')
'u' -> { sb.append(src.substring(pos, pos + 4).toInt(16).toChar()); pos += 4 }
else -> throw IllegalArgumentException("Invalid JSON")
}
else -> {
if (c < ' ') throw IllegalArgumentException("Invalid JSON")
sb.append(c)
}
}
}
}
private fun parseNumber(): Double {
val start = pos
if (src[pos] == '-') pos++
if (!src[pos].isDigit()) throw IllegalArgumentException("Invalid JSON")
while (pos < src.length && src[pos].isDigit()) pos++
if (pos < src.length && src[pos] == '.') {
pos++
if (!src[pos].isDigit()) throw IllegalArgumentException("Invalid JSON")
while (pos < src.length && src[pos].isDigit()) pos++
}
if (pos < src.length && (src[pos] == 'e' || src[pos] == 'E')) {
pos++
if (src[pos] == '-' || src[pos] == '+') pos++
if (!src[pos].isDigit()) throw IllegalArgumentException("Invalid JSON")
while (pos < src.length && src[pos].isDigit()) pos++
}
return src.substring(start, pos).toDouble()
}
}
// ---- JS-flavoured helpers ----------------------------------------------------
// Number.isInteger: finite and equal to its floor.
private fun isIntegral(v: Double) = v == Math.floor(v) && !v.isInfinite() && !v.isNaN()
private fun kindOf(v: Any?): String = when (v) {
null -> "null"
is Boolean -> "boolean"
is Double -> if (isIntegral(v)) "integer" else "number"
is List<*> -> "array"
is Map<*, *> -> "object"
else -> "string"
}
private fun deepEqual(a: Any?, b: Any?): Boolean {
if (kindOf(a) != kindOf(b)) return false
if (a == null) return true
return when (a) {
is Boolean -> a == b
is Double -> a == b
is String -> a == b
is List<*> -> {
val y = b as List<*>
a.size == y.size && a.indices.all { deepEqual(a[it], y[it]) }
}
else -> {
val x = a as Map<*, *>
val y = b as Map<*, *>
x.size == y.size && x.all { (k, v) -> y.containsKey(k) && deepEqual(v, y[k]) }
}
}
}
// JS Number-to-string: plain integers below 1e21, exponential only past the
// JS thresholds (decimal exponent < -6 or >= 21), minimal exponent digits.
fun jsNum(v: Double): String {
if (v == 0.0) return "0" // covers -0
val neg = v < 0
val a = if (neg) -v else v
if (isIntegral(a) && a < 1e21) return (if (neg) "-" else "") + BigDecimal(java.lang.Double.toString(a)).toBigInteger()
val s = java.lang.Double.toString(a) // shortest round-trip digits, Java flavour
val e = s.indexOf('E')
val mant = if (e >= 0) s.substring(0, e) else s
val eexp = if (e >= 0) s.substring(e + 1).toInt() else 0
val dot = mant.indexOf('.')
val intpart = if (dot >= 0) mant.substring(0, dot) else mant
val digits0 = intpart + if (dot >= 0) mant.substring(dot + 1) else ""
var exp = intpart.length.toLong() - 1 + eexp
var d = digits0
while (d.length > 1 && d[0] == '0') { d = d.substring(1); exp-- }
val sb = StringBuilder(if (neg) "-" else "")
when {
exp < -6 || exp >= 21 -> {
sb.append(d[0])
if (d.length > 1) sb.append('.').append(d.substring(1))
sb.append('e').append(if (exp >= 0) "+" else "").append(exp)
}
exp < 0 -> {
sb.append("0.")
for (i in 0 until (-exp - 1)) sb.append('0')
sb.append(d)
}
d.length > exp + 1 -> {
sb.append(d, 0, (exp + 1).toInt()).append('.').append(d.substring((exp + 1).toInt()))
}
else -> {
sb.append(d)
for (i in 0 until (exp + 1 - d.length)) sb.append('0')
}
}
return sb.toString()
}
// TS .length: UTF-16 code units — astral chars count as 2.
private fun utf16Len(s: String): Int {
var n = 0
var i = 0
while (i < s.length) {
val cp = s.codePointAt(i)
n += if (cp > 0xFFFF) 2 else 1
i += Character.charCount(cp)
}
return n
}
// JS String(v) for schema type entries and required keys.
private fun jsStr(v: Any?): String = when (v) {
null -> "null"
is Boolean -> if (v) "true" else "false"
is Double -> jsNum(v)
is String -> v
is List<*> -> v.joinToString(",") { jsStr(it) }
else -> "[object Object]"
}
// ---- validator -----------------------------------------------------------------
private fun addIssue(r: Result, path: String, message: String) { r.issues.add(Issue(path, message)) }
private fun validate(v: Any?, schema: Any?, path: String, r: Result) {
if (schema is Boolean) {
if (!schema) addIssue(r, path, "no value is allowed here (schema is false)")
return
}
if (schema !is Map<*, *>) {
addIssue(r, path, "invalid schema node: expected an object or boolean")
return
}
val type = schema["type"]
if (type != null) {
val entries = if (type is List<*>) type else listOf(type)
val allowed = entries.map { jsStr(it) }
val actual = kindOf(v)
if (allowed.none { it == actual || (it == "number" && actual == "integer") })
addIssue(r, path, "expected type " + allowed.joinToString("|") + ", got " + actual)
}
val en = schema["enum"]
if (en != null) {
val list = if (en is List<*>) en else emptyList<Any?>()
if (list.none { deepEqual(v, it) }) addIssue(r, path, "value not in enum (${list.size} allowed)")
}
val konst = schema["const"]
if (konst != null && !deepEqual(v, konst)) addIssue(r, path, "value does not match const")
if (v is Double && schema["minimum"] is Double && v < schema["minimum"] as Double)
addIssue(r, path, "${jsNum(v)} is less than minimum ${jsNum(schema["minimum"] as Double)}")
if (v is Double && schema["maximum"] is Double && v > schema["maximum"] as Double)
addIssue(r, path, "${jsNum(v)} is greater than maximum ${jsNum(schema["maximum"] as Double)}")
if (v is Double && schema["exclusiveMinimum"] is Double && v <= schema["exclusiveMinimum"] as Double)
addIssue(r, path, "${jsNum(v)} is not greater than exclusiveMinimum ${jsNum(schema["exclusiveMinimum"] as Double)}")
if (v is Double && schema["exclusiveMaximum"] is Double && v >= schema["exclusiveMaximum"] as Double)
addIssue(r, path, "${jsNum(v)} is not less than exclusiveMaximum ${jsNum(schema["exclusiveMaximum"] as Double)}")
if (v is String) {
val len = utf16Len(v)
if (schema["minLength"] is Double && len < schema["minLength"] as Double)
addIssue(r, path, "string length $len is less than minLength ${jsNum(schema["minLength"] as Double)}")
if (schema["maxLength"] is Double && len > schema["maxLength"] as Double)
addIssue(r, path, "string length $len is greater than maxLength ${jsNum(schema["maxLength"] as Double)}")
val pat = schema["pattern"]
if (pat is String) {
try {
if (!Regex(pat).containsMatchIn(v)) addIssue(r, path, "string does not match pattern $pat")
} catch (e: PatternSyntaxException) {
addIssue(r, path, "invalid pattern in schema: $pat")
}
}
}
if (v is List<*>) {
if (schema["minItems"] is Double && v.size < schema["minItems"] as Double)
addIssue(r, path, "array length ${v.size} is less than minItems ${jsNum(schema["minItems"] as Double)}")
if (schema["maxItems"] is Double && v.size > schema["maxItems"] as Double)
addIssue(r, path, "array length ${v.size} is greater than maxItems ${jsNum(schema["maxItems"] as Double)}")
if (schema["uniqueItems"] == true)
for (i in v.indices) for (j in i + 1 until v.size)
if (deepEqual(v[i], v[j])) addIssue(r, "$path[$j]", "duplicate item (same as index $i)")
val items = schema["items"]
if (items != null) v.forEachIndexed { i, item -> validate(item, items, "$path[$i]", r) }
}
if (v is Map<*, *>) {
val req = schema["required"]
if (req is List<*>)
for (rk in req) {
val key = jsStr(rk)
if (!v.containsKey(key)) addIssue(r, path, "missing required property \"$key\"")
}
val props = schema["properties"] as? Map<*, *>
if (props != null)
for ((k, sub) in props) {
val key = k.toString()
if (v.containsKey(key)) validate(v[key], sub!!, "$path.$key", r)
}
if (schema["additionalProperties"] == false)
for (k in v.keys)
if (props == null || !props.containsKey(k)) addIssue(r, "$path.$k", "additional property not allowed")
}
}
/** Validate a JSON document against a schema. */
fun validateJsonSchema(schemaRaw: String, instanceRaw: String): Result {
val r = Result()
if (schemaRaw.isBlank() || instanceRaw.isBlank()) {
r.error = "Both a schema and an instance are required"
return r
}
val schema = try { Parser(schemaRaw).parseDocument() } catch (e: IllegalArgumentException) {
r.error = "Schema: Invalid JSON"; return r
}
val instance = try { Parser(instanceRaw).parseDocument() } catch (e: IllegalArgumentException) {
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"
fun main() {
val r = validateJsonSchema(
"{\"type\":\"object\",\"required\":[\"port\"],\"properties\":{\"port\":{\"type\":\"integer\",\"minimum\":1024}}}",
"{\"port\":80}")
println("valid=${r.valid} issues=${r.issues.size} error=${r.error ?: "null"}")
for (i in r.issues) println(" ${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 →