Skip to content

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

// jsonpath — JSONPath query engine. C++ port (canonical TS:
// src/lib/jsonpath.ts; Go twin: cli/jsonpath). Hand-rolled strict JSON
// parser (C++ standard library only): objects keep insertion order as a
// vector of key/value pairs, so wildcard/recursive-descent match order
// matches the TS contract (\u escapes decode lone surrogates without pair
// joining). Path-error texts are byte-for-byte the TS contract; JSON parse
// errors surface the static "Invalid JSON". Matches borrow the parsed tree
// (const Json*), so the document must outlive the result. Segments: child
// / wild / descend / index / slice / union of (index|child). Filter [?()]
// and script expressions are unsupported by design.
#include <algorithm>
#include <cstddef>
#include <string>
#include <utility>
#include <vector>

struct Json {
    enum K { Nul, Bool, Num, Str, Arr, Obj } k = Nul;
    bool b = false;
    double num = 0;
    std::string s;
    std::vector<Json> items;
    std::vector<std::pair<std::string, Json>> pairs;
};

struct Part { bool isIdx = false; long n = 0; std::string name; };
struct Seg {
    int k = 0; /* 0 child 1 wild 2 descend 3 index 4 slice 5 union */
    std::string name;
    long n = 0, start = 0, end = 0;
    bool hasStart = false, hasEnd = false;
    std::vector<Part> parts;
};
struct JPMatch { std::string path; const Json *value; };
struct JPResult { std::vector<JPMatch> matches; bool ok = true; std::string error; };

namespace {

std::string jtrim(const std::string &t) {
    size_t a = t.find_first_not_of(" \t\n\r\f\v");
    if (a == std::string::npos) return "";
    size_t b = t.find_last_not_of(" \t\n\r\f\v");
    return t.substr(a, b - a + 1);
}

/* ---- strict JSON parser ---- */

struct P {
    const std::string &s;
    size_t i = 0;
    std::string err;
    explicit P(const std::string &src) : s(src) {}
    bool bad() { if (err.empty()) err = "Invalid JSON"; return false; }
    void ws() { while (i < s.size() && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == '\r')) i++; }
    bool lit(const char *w, size_t n) { if (s.compare(i, n, w) == 0) { i += n; return true; } return false; }
    bool val(Json &out) {
        ws();
        if (i >= s.size()) return bad();
        char c = s[i];
        if (c == '{') return obj(out);
        if (c == '[') return arr(out);
        if (c == '"') { out.k = Json::Str; i++; return str(out.s); }
        if (lit("true", 4)) { out.k = Json::Bool; out.b = true; return true; }
        if (lit("false", 5)) { out.k = Json::Bool; return true; }
        if (lit("null", 4)) { out.k = Json::Nul; return true; }
        if (c == '-' || (c >= '0' && c <= '9')) return num(out);
        return bad();
    }
    bool str(std::string &out) {
        while (i < s.size() && s[i] != '"') {
            char c = s[i++];
            if (c != '\\') { out.push_back(c); continue; }
            if (i >= s.size()) return bad();
            char e = s[i++];
            switch (e) {
            case '"': case '\\': case '/': out.push_back(e); break;
            case 'b': out.push_back('\b'); break;
            case 'f': out.push_back('\f'); break;
            case 'n': out.push_back('\n'); break;
            case 'r': out.push_back('\r'); break;
            case 't': out.push_back('\t'); break;
            case 'u': {
                unsigned cp = 0;
                for (int k = 0; k < 4; k++) {
                    if (i >= s.size()) return bad();
                    char h = s[i++];
                    int d = (h >= '0' && h <= '9') ? h - '0' : ((h | 32) >= 'a' && (h | 32) <= 'f') ? (h | 32) - 'a' + 10 : -1;
                    if (d < 0) return bad();
                    cp = cp * 16 + (unsigned)d;
                }
                /* terse: surrogate pairs are not joined */
                if (cp < 0x80) out.push_back((char)cp);
                else if (cp < 0x800) { out.push_back((char)(0xC0 | (cp >> 6))); out.push_back((char)(0x80 | (cp & 63))); }
                else if (cp < 0x10000) { out.push_back((char)(0xE0 | (cp >> 12))); out.push_back((char)(0x80 | ((cp >> 6) & 63))); out.push_back((char)(0x80 | (cp & 63))); }
                else { out.push_back((char)(0xF0 | (cp >> 18))); out.push_back((char)(0x80 | ((cp >> 12) & 63))); out.push_back((char)(0x80 | ((cp >> 6) & 63))); out.push_back((char)(0x80 | (cp & 63))); }
                break;
            }
            default: return bad();
            }
        }
        if (i >= s.size()) return bad();
        i++; /* closing quote */
        return true;
    }
    bool num(Json &out) {
        size_t st = i;
        if (i < s.size() && s[i] == '-') i++;
        while (i < s.size() && s[i] >= '0' && s[i] <= '9') i++;
        if (i < s.size() && s[i] == '.') { i++; while (i < s.size() && s[i] >= '0' && s[i] <= '9') i++; }
        if (i < s.size() && (s[i] == 'e' || s[i] == 'E')) {
            i++;
            if (i < s.size() && (s[i] == '+' || s[i] == '-')) i++;
            while (i < s.size() && s[i] >= '0' && s[i] <= '9') i++;
        }
        try { out.k = Json::Num; out.num = std::stod(s.substr(st, i - st)); } catch (...) { return bad(); }
        return true;
    }
    bool obj(Json &out) {
        out.k = Json::Obj;
        i++; ws();
        if (i < s.size() && s[i] == '}') { i++; return true; }
        while (true) {
            ws();
            if (i >= s.size() || s[i] != '"') return bad();
            i++;
            std::string k;
            if (!str(k)) return false;
            ws();
            if (i >= s.size() || s[i] != ':') return bad();
            i++;
            Json v;
            if (!val(v)) return false;
            out.pairs.emplace_back(std::move(k), std::move(v));
            ws();
            if (i < s.size() && s[i] == ',') { i++; continue; }
            if (i < s.size() && s[i] == '}') { i++; return true; }
            return bad();
        }
    }
    bool arr(Json &out) {
        out.k = Json::Arr;
        i++; ws();
        if (i < s.size() && s[i] == ']') { i++; return true; }
        while (true) {
            Json v;
            if (!val(v)) return false;
            out.items.push_back(std::move(v));
            ws();
            if (i < s.size() && s[i] == ',') { i++; continue; }
            if (i < s.size() && s[i] == ']') { i++; return true; }
            return bad();
        }
    }
};

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

bool nameStart(char c) { return c == '_' || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); }
bool nameChar(char c) { return nameStart(c) || c == '-' || (c >= '0' && c <= '9'); }

/* [A-Za-z_][A-Za-z0-9_-]* at i, or "" (valid names are never empty). */
std::string nameAt(const std::string &s, size_t i) {
    if (i >= s.size() || !nameStart(s[i])) return "";
    size_t j = i + 1;
    while (j < s.size() && nameChar(s[j])) j++;
    return s.substr(i, j - i);
}

/* Strict "-?\d+" (leading zeros stay decimal). */
bool intLit(const std::string &t, long &out) {
    size_t j = !t.empty() && t[0] == '-' ? 1 : 0;
    if (j >= t.size()) return false;
    long v = 0;
    for (; j < t.size(); j++) { if (t[j] < '0' || t[j] > '9') return false; v = v * 10 + (t[j] - '0'); }
    out = t[0] == '-' ? -v : v;
    return true;
}

/* '...' or "..." with the SAME quotes and none inside; 1 = name decoded. */
bool sameQuote(const std::string &t, std::string &name) {
    if (t.size() < 2) return false;
    char q = t[0];
    if ((q != '\'' && q != '"') || t.back() != q) return false;
    for (size_t j = 1; j + 1 < t.size(); j++) if (t[j] == q) return false;
    name = t.substr(1, t.size() - 2);
    return true;
}

/* Any quote ... any quote with no quotes inside (union member form). */
bool unionQuote(const std::string &t, std::string &name) {
    if (t.size() < 2) return false;
    char a = t[0], b = t.back();
    if ((a != '\'' && a != '"') || (b != '\'' && b != '"')) return false;
    for (size_t j = 1; j + 1 < t.size(); j++) if (t[j] == '\'' || t[j] == '"') return false;
    name = t.substr(1, t.size() - 2);
    return true;
}

/* "start:end" with optional int sides (ws allowed around ':'); 1 = slice. */
bool trySlice(const std::string &inner, Seg &seg) {
    size_t ci = inner.find(':');
    if (ci == std::string::npos) return false;
    std::string a = jtrim(inner.substr(0, ci)), b = jtrim(inner.substr(ci + 1));
    if (b.find(':') != std::string::npos) return false;
    if (!a.empty()) { if (!intLit(a, seg.start)) return false; seg.hasStart = true; }
    if (!b.empty()) { if (!intLit(b, seg.end)) return false; seg.hasEnd = true; }
    seg.k = 4;
    return true;
}

bool parsePath(const std::string &src, std::vector<Seg> &segs, std::string &err) {
    if (src.empty() || src[0] != '$') { err = "path must start with $"; return false; }
    size_t i = 1;
    while (i < src.size()) {
        char ch = src[i];
        if (ch == '.') {
            if (i + 1 < src.size() && src[i + 1] == '.') {
                i += 2;
                std::string m = nameAt(src, i);
                if (m.empty()) { err = "expected a name after \"..\" at position " + std::to_string(i); return false; }
                Seg s; s.k = 2; s.name = m;
                segs.push_back(s);
                i += m.size();
            } else {
                i += 1;
                if (i < src.size() && src[i] == '*') { Seg s; s.k = 1; segs.push_back(s); i++; continue; }
                std::string m = nameAt(src, i);
                if (m.empty()) { err = "expected a name or * after \".\" at position " + std::to_string(i); return false; }
                Seg s; s.k = 0; s.name = m;
                segs.push_back(s);
                i += m.size();
            }
        } else if (ch == '[') {
            size_t close = src.find(']', i);
            if (close == std::string::npos) { err = "unclosed [ at position " + std::to_string(i); return false; }
            std::string inner = jtrim(src.substr(i + 1, close - i - 1));
            i = close + 1;
            if (inner == "*") { Seg s; s.k = 1; segs.push_back(s); continue; }
            Seg s;
            if (intLit(inner, s.n)) { s.k = 3; segs.push_back(s); continue; }
            if (sameQuote(inner, s.name)) { s.k = 0; segs.push_back(s); continue; }
            if (trySlice(inner, s)) { segs.push_back(s); continue; }
            if (inner.find(',') != std::string::npos) {
                s.k = 5;
                size_t st = 0;
                while (true) {
                    size_t comma = inner.find(',', st);
                    std::string p = jtrim(inner.substr(st, (comma == std::string::npos ? inner.size() : comma) - st));
                    Part part;
                    if (intLit(p, part.n)) part.isIdx = true;
                    else if (!unionQuote(p, part.name)) { err = "bad union member \"" + p + "\" in [" + inner + "]"; return false; }
                    s.parts.push_back(part);
                    if (comma == std::string::npos) break;
                    st = comma + 1;
                }
                segs.push_back(s);
                continue;
            }
            err = "unsupported selector [" + inner + "]";
            return false;
        } else {
            err = "unexpected character \"" + std::string(1, ch) + "\" at position " + std::to_string(i);
            return false;
        }
    }
    return true;
}

/* ---- matcher ---- */

/* Recursive descent: object keys are checked then recursed (TS order). */
void descend(const Json &v, const std::string &p, const std::string &name, std::vector<JPMatch> &out) {
    if (v.k == Json::Obj) {
        for (const auto &pr : v.pairs) {
            std::string cp = p + "." + pr.first;
            if (pr.first == name) out.push_back({cp, &pr.second});
            descend(pr.second, cp, name, out);
        }
    } else if (v.k == Json::Arr) {
        for (size_t j = 0; j < v.items.size(); j++) descend(v.items[j], p + "[" + std::to_string(j) + "]", name, out);
    }
}

/* Apply one segment to every pending node, appending matches to out. */
void applySeg(const std::vector<JPMatch> &nodes, const Seg &seg, std::vector<JPMatch> &out) {
    for (const JPMatch &nd : nodes) {
        const Json &v = *nd.value;
        const std::string &p = nd.path;
        switch (seg.k) {
        case 0:
            if (v.k == Json::Obj)
                for (const auto &pr : v.pairs)
                    if (pr.first == seg.name) { out.push_back({p + "." + seg.name, &pr.second}); break; }
            break;
        case 1:
            if (v.k == Json::Arr)
                for (size_t j = 0; j < v.items.size(); j++) out.push_back({p + "[" + std::to_string(j) + "]", &v.items[j]});
            else if (v.k == Json::Obj)
                for (const auto &pr : v.pairs) out.push_back({p + "." + pr.first, &pr.second});
            break;
        case 2: descend(v, p, seg.name, out); break;
        case 3:
            if (v.k == Json::Arr) {
                long idx = seg.n < 0 ? (long)v.items.size() + seg.n : seg.n;
                if (idx >= 0 && idx < (long)v.items.size()) out.push_back({p + "[" + std::to_string(idx) + "]", &v.items[idx]});
            }
            break;
        case 4:
            if (v.k == Json::Arr) {
                long len = (long)v.items.size();
                long start = !seg.hasStart ? 0 : seg.start < 0 ? std::max(len + seg.start, 0L) : std::min(seg.start, len);
                long end = !seg.hasEnd ? len : seg.end < 0 ? std::max(len + seg.end, 0L) : std::min(seg.end, len);
                for (long j = start; j < end; j++) out.push_back({p + "[" + std::to_string(j) + "]", &v.items[j]});
            }
            break;
        case 5:
            for (const Part &part : seg.parts) {
                Seg tmp;
                if (part.isIdx) { tmp.k = 3; tmp.n = part.n; }
                else { tmp.k = 0; tmp.name = part.name; }
                std::vector<JPMatch> one = {nd};
                applySeg(one, tmp, out);
            }
            break;
        }
    }
}

} // namespace

/** Evaluate a JSONPath expression against a JSON document. */
JPResult queryJsonPath(const std::string &docRaw, const std::string &path) {
    JPResult r;
    if (jtrim(docRaw).empty() || jtrim(path).empty()) {
        r.ok = false;
        r.error = "Both a document and a path are required";
        return r;
    }
    Json doc;
    {
        P p(docRaw);
        if (!p.val(doc) || p.i < docRaw.size()) {
            r.ok = false;
            r.error = "Invalid JSON";
            return r;
        }
    }
    std::vector<Seg> segs;
    std::string err;
    if (!parsePath(jtrim(path), segs, err)) {
        r.ok = false;
        r.error = err;
        return r;
    }
    std::vector<JPMatch> cur = {JPMatch{"$", &doc}};
    for (const Seg &seg : segs) {
        std::vector<JPMatch> nxt;
        applySeg(cur, seg, nxt);
        cur = std::move(nxt);
    }
    r.matches = std::move(cur);
    return r;
}

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 →