Skip to content

JSONPath Tester — Kotlin source

Run JSONPath queries against any document: child access, wildcards, recursive descent, indexes, slices and unions, with every match shown at its full path. 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.

// jsonpath — JSONPath query engine. Kotlin port (canonical TS:
// src/lib/jsonpath.ts; Go twin: cli/jsonpath). Hand-rolled strict JSON
// parser (kotlin.stdlib only — it ships no JSON parser): objects are
// LinkedHashMap (insertion order preserved, duplicate key keeps last),
// arrays ArrayList, integer literals Long and the rest Double, so
// wildcard/descent match order and number display match the TS contract.
// Path errors are byte-for-byte the TS texts; JSON errors surface the
// static "Invalid JSON". Segments are a sealed hierarchy: child / wild /
// descend / index / slice / union of (index|child). Filter [?()] and
// script expressions are unsupported by design.

/** One match: the "$"-rooted path plus the value found there. */
data class JPMatch(val path: String, val value: Any?)

/** Result union mirror: matches + nullable error (null on success). */
data class JPResult(val matches: List<JPMatch>, val error: String?)

/** One parsed segment of the path. */
sealed interface Seg
data class ChildS(val name: String) : Seg
object WildS : Seg
data class DescendS(val name: String) : Seg
data class IndexS(val n: Long) : Seg
data class SliceS(val start: Long?, val end: Long?) : Seg
data class UnionS(val parts: List<Seg>) : Seg

private class P(val s: String) {
    var i = 0
    fun bad(): Nothing = throw IllegalStateException("Invalid JSON")
    fun ws() { while (i < s.length && s[i] in " \t\n\r") i++ }
    fun lit(w: String) {
        for (c in w) {
            if (i >= s.length || s[i] != c) bad()
            i++
        }
    }

    /** Parsed doc: LinkedHashMap / ArrayList / String / Long|Double / Boolean / null. */
    fun doc(): Any? {
        ws()
        val v = value()
        ws()
        if (i < s.length) bad()
        return v
    }

    fun value(): Any? {
        ws()
        if (i >= s.length) bad()
        return when (s[i]) {
            '{' -> obj()
            '[' -> arr()
            '"' -> { i++; str() }
            't' -> { lit("true"); true }
            'f' -> { lit("false"); false }
            'n' -> { lit("null"); null }
            else -> num()
        }
    }

    /** String body (opening quote consumed); terse: surrogates not joined. */
    fun str(): String {
        val o = StringBuilder()
        while (i < s.length && s[i] != '"') {
            val c = s[i++]
            if (c != '\\') { o.append(c); continue }
            if (i >= s.length) bad()
            when (val e = s[i++]) {
                '"', '\\', '/' -> o.append(e)
                'b' -> o.append('\b')
                'f' -> o.append('\u000C')
                'n' -> o.append('\n')
                'r' -> o.append('\r')
                't' -> o.append('\t')
                'u' -> {
                    if (i + 4 > s.length) bad()
                    var cp = 0
                    repeat(4) {
                        val d = Character.digit(s[i++], 16)
                        if (d < 0) bad()
                        cp = cp * 16 + d
                    }
                    o.appendCodePoint(cp)
                }
                else -> bad()
            }
        }
        if (i >= s.length) bad()
        i++
        return o.toString()
    }

    fun num(): Any {
        val st = i
        var flt = false
        if (i < s.length && s[i] == '-') i++
        while (i < s.length && s[i] in '0'..'9') i++
        if (i < s.length && s[i] == '.') { flt = true; i++; while (i < s.length && s[i] in '0'..'9') i++ }
        if (i < s.length && (s[i] == 'e' || s[i] == 'E')) {
            flt = true
            i++
            if (i < s.length && (s[i] == '+' || s[i] == '-')) i++
            while (i < s.length && s[i] in '0'..'9') i++
        }
        val t = s.substring(st, i)
        return if (flt) t.toDouble() else try { t.toLong() } catch (e: NumberFormatException) { t.toDouble() }
    }

    fun obj(): Any {
        val m = LinkedHashMap<String, Any?>()
        i++
        ws()
        if (i < s.length && s[i] == '}') { i++; return m }
        while (true) {
            ws()
            if (i >= s.length || s[i] != '"') bad()
            i++
            val k = str()
            ws()
            if (i >= s.length || s[i] != ':') bad()
            i++
            m[k] = value()
            ws()
            if (i < s.length && s[i] == ',') { i++; continue }
            if (i < s.length && s[i] == '}') { i++; return m }
            bad()
        }
    }

    fun arr(): Any {
        val a = ArrayList<Any?>()
        i++
        ws()
        if (i < s.length && s[i] == ']') { i++; return a }
        while (true) {
            a.add(value())
            ws()
            if (i < s.length && s[i] == ',') { i++; continue }
            if (i < s.length && s[i] == ']') { i++; return a }
            bad()
        }
    }
}

private fun nameStart(c: Char) = c == '_' || c in 'A'..'Z' || c in 'a'..'z'
private fun nameChar(c: Char) = nameStart(c) || c == '-' || c in '0'..'9'

/** [A-Za-z_][A-Za-z0-9_-]* at i, or null (valid names are never empty). */
private fun nameAt(t: String, at: Int): String? {
    if (at >= t.length || !nameStart(t[at])) return null
    var j = at + 1
    while (j < t.length && nameChar(t[j])) j++
    return t.substring(at, j)
}

/** Strict "-?\d+" (leading zeros stay decimal). */
private fun intLit(t: String): Boolean {
    val j = if (t.startsWith("-")) 1 else 0
    if (j >= t.length) return false
    for (q in j until t.length) { val c = t[q]; if (c < '0' || c > '9') return false }
    return true
}

/** '...' or "..." with the SAME quotes and none inside; else null. */
private fun sameQuote(t: String): String? {
    if (t.length < 2) return null
    val q = t[0]
    if (q != '\'' && q != '"') return null
    if (t[t.length - 1] != q) return null
    for (j in 1 until t.length - 1) if (t[j] == q) return null
    return t.substring(1, t.length - 1)
}

/** Any quote ... any quote with no quotes inside (union member form). */
private fun unionQuote(t: String): String? {
    if (t.length < 2) return null
    val a = t[0]
    val b = t[t.length - 1]
    if (a != '\'' && a != '"') return null
    if (b != '\'' && b != '"') return null
    for (j in 1 until t.length - 1) if (t[j] == '\'' || t[j] == '"') return null
    return t.substring(1, t.length - 1)
}

/** "start:end" with optional int sides (ws allowed around ':'). */
private fun trySlice(inner: String): SliceS? {
    val ci = inner.indexOf(':')
    if (ci < 0) return null
    val a = inner.substring(0, ci).trim()
    val b = inner.substring(ci + 1).trim()
    if (b.contains(':')) return null
    if (a.isNotEmpty() && !intLit(a)) return null
    if (b.isNotEmpty() && !intLit(b)) return null
    return SliceS(if (a.isEmpty()) null else a.toLong(), if (b.isEmpty()) null else b.toLong())
}

/** Tokenize+parse; throws IllegalStateException with the TS error text. */
private fun parsePath(src: String): List<Seg> {
    val segs = ArrayList<Seg>()
    if (src.isEmpty() || src[0] != '$') throw IllegalStateException("path must start with \$")
    var i = 1
    while (i < src.length) {
        val ch = src[i]
        if (ch == '.') {
            if (i + 1 < src.length && src[i + 1] == '.') {
                i += 2
                val m = nameAt(src, i) ?: throw IllegalStateException("expected a name after \"..\" at position $i")
                segs.add(DescendS(m))
                i += m.length
            } else {
                i += 1
                if (i < src.length && src[i] == '*') { segs.add(WildS); i += 1; continue }
                val m = nameAt(src, i) ?: throw IllegalStateException("expected a name or * after \".\" at position $i")
                segs.add(ChildS(m))
                i += m.length
            }
        } else if (ch == '[') {
            val close = src.indexOf(']', i)
            if (close < 0) throw IllegalStateException("unclosed [ at position $i")
            val inner = src.substring(i + 1, close).trim()
            i = close + 1
            if (inner == "*") { segs.add(WildS); continue }
            if (intLit(inner)) { segs.add(IndexS(inner.toLong())); continue }
            val nm = sameQuote(inner)
            if (nm != null) { segs.add(ChildS(nm)); continue }
            val sl = trySlice(inner)
            if (sl != null) { segs.add(sl); continue }
            if (inner.contains(',')) {
                val parts = ArrayList<Seg>()
                for (raw in inner.split(",")) {
                    val p = raw.trim()
                    if (intLit(p)) parts.add(IndexS(p.toLong()))
                    else {
                        val un = unionQuote(p)
                            ?: throw IllegalStateException("bad union member \"$p\" in [$inner]")
                        parts.add(ChildS(un))
                    }
                }
                segs.add(UnionS(parts))
                continue
            }
            throw IllegalStateException("unsupported selector [$inner]")
        } else {
            throw IllegalStateException("unexpected character \"$ch\" at position $i")
        }
    }
    return segs
}

/** Recursive descent: object keys are checked then recursed (TS order). */
private fun descend(v: Any?, p: String, name: String, out: MutableList<JPMatch>) {
    when (v) {
        is Map<*, *> -> for ((k, child) in v) {
            val cp = "$p.$k"
            if (k == name) out.add(JPMatch(cp, child))
            descend(child, cp, name, out)
        }
        is List<*> -> v.forEachIndexed { idx, item -> descend(item, "$p[$idx]", name, out) }
    }
}

/** Apply one segment to every pending node, appending matches to out. */
private fun applySeg(nodes: List<JPMatch>, seg: Seg, out: MutableList<JPMatch>) {
    for (nd in nodes) {
        val v = nd.value
        val p = nd.path
        when (seg) {
            is ChildS -> if (v is Map<*, *> && v.containsKey(seg.name)) out.add(JPMatch("$p.${seg.name}", v[seg.name]))
            is WildS -> when (v) {
                is List<*> -> v.forEachIndexed { idx, item -> out.add(JPMatch("$p[$idx]", item)) }
                is Map<*, *> -> for ((k, child) in v) out.add(JPMatch("$p.$k", child))
            }
            is DescendS -> descend(v, p, seg.name, out)
            is IndexS -> if (v is List<*>) {
                val idx = if (seg.n < 0) v.size + seg.n else seg.n
                if (idx >= 0 && idx < v.size) out.add(JPMatch("$p[$idx]", v[idx.toInt()]))
            }
            is SliceS -> if (v is List<*>) {
                val len = v.size.toLong()
                val start = if (seg.start == null) 0L else if (seg.start < 0) maxOf(len + seg.start, 0L) else minOf(seg.start, len)
                val end = if (seg.end == null) len else if (seg.end < 0) maxOf(len + seg.end, 0L) else minOf(seg.end, len)
                for (idx in start until end) out.add(JPMatch("$p[$idx]", v[idx.toInt()]))
            }
            is UnionS -> for (part in seg.parts) applySeg(listOf(nd), part, out)
        }
    }
}

/** Evaluate a JSONPath expression against a JSON document. */
fun queryJsonPath(docRaw: String, path: String): JPResult {
    if (docRaw.isBlank() || path.isBlank()) {
        return JPResult(emptyList(), "Both a document and a path are required")
    }
    val doc = try {
        P(docRaw).doc()
    } catch (e: IllegalStateException) {
        return JPResult(emptyList(), "Invalid JSON")
    }
    val segs = try {
        parsePath(path.trim())
    } catch (e: IllegalStateException) {
        return JPResult(emptyList(), e.message)
    }
    var cur = listOf(JPMatch("$", doc))
    for (seg in segs) {
        val nxt = ArrayList<JPMatch>()
        applySeg(cur, seg, nxt)
        cur = nxt
    }
    return JPResult(cur, null)
}

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 →