Skip to content

JSONPath Tester — Java 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 Java implementation — the same logic the interactive tool runs, in a shareable, citable form.

// jsonpath — JSONPath query engine. Java port (canonical TS:
// src/lib/jsonpath.ts; Go twin: cli/jsonpath). Hand-rolled strict JSON
// parser (java.util only — the JDK 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: child / wild / descend / index / slice
// / union of (index|child). Filter [?()] and script expressions are
// unsupported by design. The parse helpers hold static cursor state
// (single-threaded display snippet).

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/** One match: the "$"-rooted path plus the value found there. */
final class JPMatch {
    final String path;
    final Object value;
    JPMatch(String path, Object value) { this.path = path; this.value = value; }
}

/** Result union mirror: matches + nullable error (null on success). */
final class JPResult {
    final List<JPMatch> matches;
    final String error;
    JPResult(List<JPMatch> matches, String error) { this.matches = matches; this.error = error; }
}

// Package-private: display snippets keep the repo filename (jsonpath.java),
// which need not match the class name.
final class JsonPath {

    /** One parsed segment; factory helpers keep construction terse. */
    static final class Seg {
        final String k;
        final String name;
        final long n;
        final Long start, end;
        final List<Seg> parts;
        private Seg(String k, String name, long n, Long start, Long end, List<Seg> parts) {
            this.k = k; this.name = name; this.n = n; this.start = start; this.end = end; this.parts = parts;
        }
        static Seg child(String name) { return new Seg("child", name, 0, null, null, null); }
        static Seg wild() { return new Seg("wild", null, 0, null, null, null); }
        static Seg descend(String name) { return new Seg("descend", name, 0, null, null, null); }
        static Seg index(long n) { return new Seg("index", null, n, null, null, null); }
        static Seg slice(Long start, Long end) { return new Seg("slice", null, 0, start, end, null); }
        static Seg union(List<Seg> parts) { return new Seg("union", null, 0, null, null, parts); }
    }

    private JsonPath() {}

    // ---- strict JSON parser (static cursor; single-threaded) ----
    private static String s;
    private static int i;

    private static IllegalStateException fail() { throw new IllegalStateException("Invalid JSON"); }
    private static void ws() { while (i < s.length() && " \t\n\r".indexOf(s.charAt(i)) >= 0) i++; }
    private static void lit(String w) {
        for (int j = 0; j < w.length(); j++) {
            if (i >= s.length() || s.charAt(i) != w.charAt(j)) throw fail();
            i++;
        }
    }

    /** Parsed doc: LinkedHashMap / ArrayList / String / Long|Double / Boolean / null. */
    static Object parseJson(String t) {
        s = t;
        i = 0;
        ws();
        Object v = val();
        ws();
        if (i < s.length()) throw fail();
        return v;
    }

    private static Object val() {
        ws();
        if (i >= s.length()) throw fail();
        char c = s.charAt(i);
        if (c == '{') return obj();
        if (c == '[') return arr();
        if (c == '"') { i++; return str(); }
        if (c == 't') { lit("true"); return Boolean.TRUE; }
        if (c == 'f') { lit("false"); return Boolean.FALSE; }
        if (c == 'n') { lit("null"); return null; }
        return num();
    }

    /** String body (opening quote consumed); terse: surrogates not joined. */
    private static String str() {
        StringBuilder o = new StringBuilder();
        while (i < s.length() && s.charAt(i) != '"') {
            char c = s.charAt(i++);
            if (c != '\\') { o.append(c); continue; }
            if (i >= s.length()) throw fail();
            char e = s.charAt(i++);
            if (e == '"' || e == '\\' || e == '/') o.append(e);
            else if (e == 'b') o.append('\b');
            else if (e == 'f') o.append('\f');
            else if (e == 'n') o.append('\n');
            else if (e == 'r') o.append('\r');
            else if (e == 't') o.append('\t');
            else if (e == 'u') {
                if (i + 4 > s.length()) throw fail();
                int cp = 0;
                for (int k = 0; k < 4; k++) {
                    int d = Character.digit(s.charAt(i++), 16);
                    if (d < 0) throw fail();
                    cp = cp * 16 + d;
                }
                o.appendCodePoint(cp);
            } else throw fail();
        }
        if (i >= s.length()) throw fail();
        i++;
        return o.toString();
    }

    private static Object num() {
        int st = i;
        boolean flt = false;
        if (i < s.length() && s.charAt(i) == '-') i++;
        while (i < s.length() && s.charAt(i) >= '0' && s.charAt(i) <= '9') i++;
        if (i < s.length() && s.charAt(i) == '.') { flt = true; i++; while (i < s.length() && s.charAt(i) >= '0' && s.charAt(i) <= '9') i++; }
        if (i < s.length() && (s.charAt(i) == 'e' || s.charAt(i) == 'E')) {
            flt = true;
            i++;
            if (i < s.length() && (s.charAt(i) == '+' || s.charAt(i) == '-')) i++;
            while (i < s.length() && s.charAt(i) >= '0' && s.charAt(i) <= '9') i++;
        }
        String t = s.substring(st, i);
        try {
            return flt ? (Object) Double.parseDouble(t) : (Object) Long.parseLong(t);
        } catch (NumberFormatException e) {
            return Double.parseDouble(t); /* long overflow → double (1e999 → Infinity) */
        }
    }

    private static Object obj() {
        Map<String, Object> m = new LinkedHashMap<>();
        i++;
        ws();
        if (i < s.length() && s.charAt(i) == '}') { i++; return m; }
        while (true) {
            ws();
            if (i >= s.length() || s.charAt(i) != '"') throw fail();
            i++;
            String k = str();
            ws();
            if (i >= s.length() || s.charAt(i) != ':') throw fail();
            i++;
            m.put(k, val());
            ws();
            if (i < s.length() && s.charAt(i) == ',') { i++; continue; }
            if (i < s.length() && s.charAt(i) == '}') { i++; return m; }
            throw fail();
        }
    }

    private static Object arr() {
        List<Object> a = new ArrayList<>();
        i++;
        ws();
        if (i < s.length() && s.charAt(i) == ']') { i++; return a; }
        while (true) {
            a.add(val());
            ws();
            if (i < s.length() && s.charAt(i) == ',') { i++; continue; }
            if (i < s.length() && s.charAt(i) == ']') { i++; return a; }
            throw fail();
        }
    }

    // ---- path tokenizer ----

    private static boolean nameStart(char c) { return c == '_' || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); }
    private static boolean nameChar(char c) { return nameStart(c) || c == '-' || (c >= '0' && c <= '9'); }
    private static IllegalStateException err(String m) { return new IllegalStateException(m); }

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

    /** Strict "-?\d+" (leading zeros stay decimal). */
    private static boolean intLit(String t) {
        int j = t.startsWith("-") ? 1 : 0;
        if (j >= t.length()) return false;
        for (int q = j; q < t.length(); q++) { char c = t.charAt(q); if (c < '0' || c > '9') return false; }
        return true;
    }

    /** '...' or "..." with the SAME quotes and none inside; else null. */
    private static String sameQuote(String t) {
        if (t.length() < 2) return null;
        char q = t.charAt(0);
        if ((q != '\'' && q != '"') || t.charAt(t.length() - 1) != q) return null;
        for (int j = 1; j + 1 < t.length(); j++) if (t.charAt(j) == q) return null;
        return t.substring(1, t.length() - 1);
    }

    /** Any quote ... any quote with no quotes inside (union member form). */
    private static String unionQuote(String t) {
        if (t.length() < 2) return null;
        char a = t.charAt(0), b = t.charAt(t.length() - 1);
        if ((a != '\'' && a != '"') || (b != '\'' && b != '"')) return null;
        for (int j = 1; j + 1 < t.length(); j++) if (t.charAt(j) == '\'' || t.charAt(j) == '"') return null;
        return t.substring(1, t.length() - 1);
    }

    /** "start:end" with optional int sides (ws allowed around ':'). */
    private static Seg trySlice(String inner) {
        int ci = inner.indexOf(':');
        if (ci < 0) return null;
        String a = inner.substring(0, ci).trim(), b = inner.substring(ci + 1).trim();
        if (b.indexOf(':') >= 0) return null;
        if (!a.isEmpty() && !intLit(a)) return null;
        if (!b.isEmpty() && !intLit(b)) return null;
        return Seg.slice(a.isEmpty() ? null : Long.valueOf(a), b.isEmpty() ? null : Long.valueOf(b));
    }

    /** Tokenize+parse; throws IllegalStateException with the TS error text. */
    private static List<Seg> parsePath(String src) {
        List<Seg> segs = new ArrayList<>();
        if (src.isEmpty() || src.charAt(0) != '$') throw err("path must start with $");
        int i = 1;
        while (i < src.length()) {
            char ch = src.charAt(i);
            if (ch == '.') {
                if (i + 1 < src.length() && src.charAt(i + 1) == '.') {
                    i += 2;
                    String m = nameAt(src, i);
                    if (m == null) throw err("expected a name after \"..\" at position " + i);
                    segs.add(Seg.descend(m));
                    i += m.length();
                } else {
                    i += 1;
                    if (i < src.length() && src.charAt(i) == '*') { segs.add(Seg.wild()); i += 1; continue; }
                    String m = nameAt(src, i);
                    if (m == null) throw err("expected a name or * after \".\" at position " + i);
                    segs.add(Seg.child(m));
                    i += m.length();
                }
            } else if (ch == '[') {
                int close = src.indexOf(']', i);
                if (close < 0) throw err("unclosed [ at position " + i);
                String inner = src.substring(i + 1, close).trim();
                i = close + 1;
                if (inner.equals("*")) { segs.add(Seg.wild()); continue; }
                if (intLit(inner)) { segs.add(Seg.index(Long.parseLong(inner))); continue; }
                String nm = sameQuote(inner);
                if (nm != null) { segs.add(Seg.child(nm)); continue; }
                Seg sl = trySlice(inner);
                if (sl != null) { segs.add(sl); continue; }
                if (inner.indexOf(',') >= 0) {
                    List<Seg> parts = new ArrayList<>();
                    for (String raw : inner.split(",", -1)) {
                        String p = raw.trim();
                        if (intLit(p)) parts.add(Seg.index(Long.parseLong(p)));
                        else {
                            String un = unionQuote(p);
                            if (un == null) throw err("bad union member \"" + p + "\" in [" + inner + "]");
                            parts.add(Seg.child(un));
                        }
                    }
                    segs.add(Seg.union(parts));
                    continue;
                }
                throw err("unsupported selector [" + inner + "]");
            } else {
                throw err("unexpected character \"" + ch + "\" at position " + i);
            }
        }
        return segs;
    }

    // ---- matcher ----

    /** Recursive descent: object keys are checked then recursed (TS order). */
    private static void descend(Object v, String p, String name, List<JPMatch> out) {
        if (v instanceof Map<?, ?> m) {
            for (Map.Entry<?, ?> e : m.entrySet()) {
                String cp = p + "." + e.getKey();
                if (e.getKey().equals(name)) out.add(new JPMatch(cp, e.getValue()));
                descend(e.getValue(), cp, name, out);
            }
        } else if (v instanceof List<?> a) {
            for (int j = 0; j < a.size(); j++) descend(a.get(j), p + "[" + j + "]", name, out);
        }
    }

    /** Apply one segment to every pending node, appending matches to out. */
    private static void applySeg(List<JPMatch> nodes, Seg seg, List<JPMatch> out) {
        for (JPMatch nd : nodes) {
            Object v = nd.value;
            String p = nd.path;
            switch (seg.k) {
                case "child" -> { if (v instanceof Map<?, ?> m && m.containsKey(seg.name)) out.add(new JPMatch(p + "." + seg.name, m.get(seg.name))); }
                case "wild" -> {
                    if (v instanceof List<?> a) { for (int j = 0; j < a.size(); j++) out.add(new JPMatch(p + "[" + j + "]", a.get(j))); }
                    else if (v instanceof Map<?, ?> m) { for (Map.Entry<?, ?> e : m.entrySet()) out.add(new JPMatch(p + "." + e.getKey(), e.getValue())); }
                }
                case "descend" -> descend(v, p, seg.name, out);
                case "index" -> {
                    if (v instanceof List<?> a) {
                        int idx = seg.n < 0 ? a.size() + (int) seg.n : (int) seg.n;
                        if (idx >= 0 && idx < a.size()) out.add(new JPMatch(p + "[" + idx + "]", a.get(idx)));
                    }
                }
                case "slice" -> {
                    if (v instanceof List<?> a) {
                        int len = a.size();
                        int start = seg.start == null ? 0 : seg.start < 0 ? (int) Math.max(len + seg.start, 0) : (int) Math.min(seg.start, len);
                        int end = seg.end == null ? len : seg.end < 0 ? (int) Math.max(len + seg.end, 0) : (int) Math.min(seg.end, len);
                        for (int j = start; j < end; j++) out.add(new JPMatch(p + "[" + j + "]", a.get(j)));
                    }
                }
                case "union" -> { for (Seg part : seg.parts) applySeg(List.of(nd), part, out); }
            }
        }
    }

    /** Evaluate a JSONPath expression against a JSON document. */
    static JPResult queryJsonPath(String docRaw, String path) {
        if (docRaw.trim().isEmpty() || path.trim().isEmpty()) {
            return new JPResult(List.of(), "Both a document and a path are required");
        }
        Object doc;
        try {
            doc = parseJson(docRaw);
        } catch (IllegalStateException e) {
            return new JPResult(List.of(), "Invalid JSON");
        }
        List<Seg> segs;
        try {
            segs = parsePath(path.trim());
        } catch (IllegalStateException e) {
            return new JPResult(List.of(), e.getMessage());
        }
        List<JPMatch> cur = new ArrayList<>();
        cur.add(new JPMatch("$", doc));
        for (Seg seg : segs) {
            List<JPMatch> nxt = new ArrayList<>();
            applySeg(cur, seg, nxt);
            cur = nxt;
        }
        return new 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 →