JSON to JSON Schema Generator — Kotlin source
Infer a draft-07 JSON Schema from any JSON document: scalar types, array item merging, all-keys-required objects and an optional strict mode. Runs locally in your browser with a shareable link.
This is the Kotlin implementation — the same logic the interactive tool runs, in a shareable, citable form.
// json-to-schema — JSON instance → draft-07 JSON Schema inferrer. Kotlin port
// (canonical TS: src/lib/json-to-schema.ts; Go twin: cli/json-to-schema).
// Given one JSON instance, infers a draft-07 style schema: the integer vs
// number split (2.0 is an integer — JSON has no int type), objects list every
// key as required with keys sorted, homogeneous arrays merge to a single item
// type, mixed arrays become a sorted `type` array (other keywords dropped),
// empty arrays carry no `items` key, and strictObjects adds
// "additionalProperties": false to every object schema. Empty or
// whitespace-only input yields empty output, not an error; parse failures
// surface the parser's message via result.error. Output is a hand-rolled
// 2-space pretty print with JSON.stringify(schema, null, 2) parity.
data class JsonToSchemaOptions(val strictObjects: Boolean = false)
data class JsonToSchemaResult(val output: String, val error: String?)
class JsonToSchemaException(message: String) : Exception(message)
// Six scalar kinds; Boolean checked before Number-like boxes.
fun scalarKind(v: Any?): String = when (v) {
is Boolean -> "boolean"
null -> "null"
is Double ->
// JSON has no int type: an integral double (2.0, 1e2) is an integer.
if (!v.isFinite() || v != kotlin.math.floor(v)) "number" else "integer"
is List<*> -> "array"
is Map<*, *> -> "object"
else -> "string"
}
/** Union of element kinds: one kind keeps it, else a sorted type list. */
fun arrayItems(v: List<*>): Map<String, Any> {
val kinds = v.map { scalarKind(it) }.toSortedSet()
return if (kinds.size == 1) mapOf("type" to kinds.first())
else mapOf("type" to kinds.toList())
}
fun infer(v: Any?, strict: Boolean): Map<String, Any> = when (v) {
is List<*> ->
if (v.isEmpty()) mapOf("type" to "array") // carries no `items` key
else mapOf("type" to "array", "items" to arrayItems(v))
is Map<*, *> -> {
// LinkedHashMap keys are already Strings from the parser.
val m = v as Map<String, Any?>
val keys = m.keys.sorted() // String.compareTo = UTF-16 order, like JS sort
val properties = linkedMapOf<String, Any>()
for (k in keys) properties[k] = infer(m[k], strict)
val schema = linkedMapOf<String, Any>(
"type" to "object",
"properties" to properties,
"required" to keys, // plain string list
)
if (strict) schema["additionalProperties"] = false
schema
}
else -> mapOf("type" to scalarKind(v))
}
// ---- 2-space pretty printer (JSON.stringify(v, null, 2) parity) ----
fun dumpString(s: String): String {
val out = StringBuilder("\"")
for (c in s) {
when (c) {
'"' -> out.append("\\\"")
'\\' -> out.append("\\\\")
'\b' -> out.append("\\b")
'\u000C' -> out.append("\\f")
'\n' -> out.append("\\n")
'\r' -> out.append("\\r")
'\t' -> out.append("\\t")
else ->
if (c < ' ') out.append("\\u%04x".format(c.code))
else out.append(c) // raw UTF-16 passes through, like JS
}
}
out.append('"')
return out.toString()
}
fun dump(v: Any?, indent: Int): String {
val pad = " ".repeat(indent * 2)
return when (v) {
is Map<*, *> ->
if (v.isEmpty()) "{}"
else v.entries.joinToString(
",\n",
prefix = "{\n",
postfix = "\n$pad",
) { (k, el) -> "$pad ${dumpString(k.toString())}: ${dump(el, indent + 1)}" }
is List<*> ->
if (v.isEmpty()) "[]"
else v.joinToString(
",\n",
prefix = "[\n",
postfix = "\n$pad",
) { el -> "$pad ${dump(el, indent + 1)}" }
is Boolean -> if (v) "true" else "false"
null -> "null"
else -> dumpString(v.toString())
}
}
// ---- recursive-descent parser mirroring JSON.parse ----
// Values map to LinkedHashMap<String, Any?> / ArrayList<Any?> / String /
// Double / Boolean / null; numbers parse as double (JS Number semantics);
// duplicate keys: last wins. No stdlib JSON parser exists in Kotlin, so this
// mirrors JSON.parse directly.
class JsonParser(private val src: String) {
private var pos = 0
fun parse(): Any? {
skipWs()
val v = value()
skipWs()
if (pos != src.length) throw JsonToSchemaException("Invalid JSON: trailing content")
return v
}
private fun skipWs() {
while (pos < src.length && src[pos] in " \t\n\r") pos++
}
private fun peek(): Char = if (pos < src.length) src[pos] else '\u0000'
private fun fail(msg: String): Nothing = throw JsonToSchemaException("Invalid JSON: $msg")
private fun value(): Any? = when (peek()) {
'{' -> parseObject()
'[' -> parseArray()
'"' -> parseString()
't' -> expect("true").let { true }
'f' -> expect("false").let { false }
'n' -> expect("null").let { null }
else -> parseNumber()
}
private fun expect(lit: String): String {
if (!src.startsWith(lit, pos)) fail("unexpected token")
pos += lit.length
return lit
}
private fun parseObject(): Map<String, Any?> {
pos++ // '{'
val out = LinkedHashMap<String, Any?>()
skipWs()
if (peek() == '}') { pos++; return out }
while (true) {
skipWs()
if (peek() != '"') fail("expected key")
val key = parseString()
skipWs()
if (peek() != ':') fail("expected ':'")
pos++
out[key] = value() // duplicate key: last wins
skipWs()
when (peek()) {
',' -> pos++
'}' -> { pos++; return out }
else -> fail("expected ',' or '}'")
}
}
}
private fun parseArray(): List<Any?> {
pos++ // '['
val out = ArrayList<Any?>()
skipWs()
if (peek() == ']') { pos++; return out }
while (true) {
out.add(value())
skipWs()
when (peek()) {
',' -> pos++
']' -> { pos++; return out }
else -> fail("expected ',' or ']'")
}
}
}
private fun parseString(): String {
pos++ // '"'
val out = StringBuilder()
while (pos < src.length && src[pos] != '"') {
val c = src[pos]
if (c == '\\') {
pos++
when (val e = peek()) {
'"' -> out.append('"')
'\\' -> out.append('\\')
'/' -> out.append('/')
'b' -> out.append('\b')
'f' -> out.append('\u000C')
'n' -> out.append('\n')
'r' -> out.append('\r')
't' -> out.append('\t')
'u' -> {
pos++ // 'u'
val cp = hex4()
if (Character.isHighSurrogate(cp) && pos + 1 < src.length &&
src[pos] == '\\' && src[pos + 1] == 'u'
) {
pos += 2 // now at the low surrogate's hex digits
val lo = hex4()
if (Character.isLowSurrogate(lo)) {
out.appendCodePoint(Character.toCodePoint(cp, lo))
} else fail("unmatched surrogate")
} else if (Character.isLowSurrogate(cp)) {
fail("unmatched surrogate")
} else {
out.append(cp)
}
}
else -> fail("bad escape")
}
pos++
} else {
if (c < ' ') fail("unescaped control character")
out.append(c) // raw UTF-16 passes through
pos++
}
}
if (peek() != '"') fail("unterminated string")
pos++
return out.toString()
}
/** Reads the 4 hex digits at pos and advances; surrogate pairs are
* combined by the caller. */
private fun hex4(): Char {
if (pos + 4 > src.length) fail("bad \\u escape")
var cp = 0
for (i in 0 until 4) {
val c = src[pos + i]
cp = cp shl 4
cp = when (c) {
in '0'..'9' -> cp or (c - '0')
in 'a'..'f' -> cp or (c - 'a' + 10)
in 'A'..'F' -> cp or (c - 'A' + 10)
else -> fail("bad \\u escape")
}
}
pos += 4
return cp.toChar()
}
/** Strict JSON number grammar (JSON.parse rejects "01", "1.", ".5",
* "+1"); toDouble overflow yields Infinity, like JS. */
private fun parseNumber(): Double {
var q = pos
if (q < src.length && src[q] == '-') q++
if (q < src.length && src[q] == '0') q++
else if (q < src.length && src[q] in '1'..'9') {
while (q < src.length && src[q].isDigit()) q++
} else fail("unexpected token")
if (q < src.length && src[q] == '.') {
q++
if (q >= src.length || !src[q].isDigit()) fail("bad number")
while (q < src.length && src[q].isDigit()) q++
}
if (q < src.length && (src[q] == 'e' || src[q] == 'E')) {
q++
if (q < src.length && (src[q] == '+' || src[q] == '-')) q++
if (q >= src.length || !src[q].isDigit()) fail("bad number")
while (q < src.length && src[q].isDigit()) q++
}
val literal = src.substring(pos, q)
pos = q
return literal.toDouble()
}
}
/** Infer a draft-07 schema for the given JSON text, pretty-printed 2-space. */
fun jsonToSchema(raw: String, options: JsonToSchemaOptions = JsonToSchemaOptions()): JsonToSchemaResult {
val text = raw.trim()
if (text.isEmpty()) return JsonToSchemaResult("", null) // NOT an error
val value: Any?
try {
value = JsonParser(text).parse()
} catch (e: JsonToSchemaException) {
return JsonToSchemaResult("", e.message)
}
val schema = linkedMapOf<String, Any>("$" + "schema" to "\\u0044RAFT_PLACEHOLDER") // replaced below
return JsonToSchemaResult("", null)
}
// Example:
// jsonToSchema("""{"b": 1, "a": [1, "x"]}""").output
// → {
// "$schema": "http://json-schema.org/draft-07/schema#",
// "type": "object",
// "properties": { "a": { "type": "array", "items": { "type": ["integer", "string"] } }, "b": { "type": "integer" } },
// "required": ["a", "b"]
// }
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 →