JSONPath Tester — Zig 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 Zig implementation — the same logic the interactive tool runs, in a shareable, citable form.
// jsonpath — JSONPath query engine. Zig port (canonical TS:
// src/lib/jsonpath.ts; Go twin: cli/jsonpath). JSON via the standard
// library (std.json): Value objects are an insertion-ordered
// StringArrayHashMap, so wildcard/descent match order matches the TS
// contract. Path errors are byte-for-byte the TS texts; std.json reports
// no message, so parse failures surface the static "Invalid JSON". All
// result memory (paths, match slice, document tree) lives in the
// caller-provided arena. Segments: child / wild / descend / index / slice
// / union of (index|child). Filter [?()] and script expressions are
// unsupported by design. Zig 0.17 (unmanaged ArrayList, like the Zig
// siblings).
const std = @import("std");
const Value = std.json.Value;
/// One match: the "$"-rooted path plus the value found there.
const JPMatch = struct { path: []u8, value: Value };
/// One parsed segment of the path.
const Seg = union(enum) {
child: []const u8,
wild,
descend: []const u8,
index: i64,
slice: struct { start: ?i64, end: ?i64 },
union_: []const Part,
};
const Part = union(enum) { index: i64, child: []const u8 };
/// Result union mirror: matches + nullable error (null on success).
const JPResult = struct { matches: []JPMatch = &.{}, err: ?[]const u8 = null };
const PathParsed = struct { segs: []Seg = &.{}, err: ?[]const u8 = null };
fn isNameStart(c: u8) bool {
return c == '_' or (c >= 'A' and c <= 'Z') or (c >= 'a' and c <= 'z');
}
fn isNameChar(c: u8) bool {
return isNameStart(c) or c == '-' or (c >= '0' and c <= '9');
}
/// [A-Za-z_][A-Za-z0-9_-]* at i, or null (valid names are never empty).
fn nameAt(s: []const u8, i: usize) ?[]const u8 {
if (i >= s.len or !isNameStart(s[i])) return null;
var j = i + 1;
while (j < s.len and isNameChar(s[j])) j += 1;
return s[i..j];
}
/// Strict "-?\d+" (leading zeros stay decimal).
fn intLit(t: []const u8) bool {
var j: usize = if (t.len > 0 and t[0] == '-') 1 else 0;
if (j >= t.len) return false;
while (j < t.len) : (j += 1) {
if (t[j] < '0' or t[j] > '9') return false;
}
return true;
}
/// intLit must hold; overflow saturates so absurd indexes never match.
fn parseIntSat(t: []const u8) i64 {
return std.fmt.parseInt(i64, t, 10) catch
if (t[0] == '-') std.math.minInt(i64) else std.math.maxInt(i64);
}
/// '...' or "..." with the SAME quotes and none inside; else null.
fn sameQuote(t: []const u8) ?[]const u8 {
if (t.len < 2) return null;
const q = t[0];
if (q != '\'' and q != '"') return null;
if (t[t.len - 1] != q) return null;
for (t[1 .. t.len - 1]) |c| {
if (c == q) return null;
}
return t[1 .. t.len - 1];
}
/// Any quote ... any quote with no quotes inside (union member form).
fn unionQuote(t: []const u8) ?[]const u8 {
if (t.len < 2) return null;
if (t[0] != '\'' and t[0] != '"') return null;
const q = t[t.len - 1];
if (q != '\'' and q != '"') return null;
for (t[1 .. t.len - 1]) |c| {
if (c == '\'' or c == '"') return null;
}
return t[1 .. t.len - 1];
}
/// "start:end" with optional int sides (ws allowed around ':').
fn trySlice(inner: []const u8, arena: std.mem.Allocator) ?Seg {
const ci = std.mem.indexOfScalar(u8, inner, ':') orelse return null;
const a = std.mem.trim(u8, inner[0..ci], WS);
const b = std.mem.trim(u8, inner[ci + 1 ..], WS);
if (std.mem.indexOfScalar(u8, b, ':') != null) return null;
var st: ?i64 = null;
var en: ?i64 = null;
if (a.len > 0) {
if (!intLit(a)) return null;
st = parseIntSat(a);
}
if (b.len > 0) {
if (!intLit(b)) return null;
en = parseIntSat(b);
}
return .{ .slice = .{ .start = st, .end = en } };
}
const WS = " \t\n\r\u{0b}\u{0c}";
fn oom() JPResult {
return .{ .err = "out of memory" };
}
/// Tokenize+parse; err carries the TS error text byte-for-byte.
fn parsePath(src: []const u8, arena: std.mem.Allocator) PathParsed {
var segs: std.ArrayList(Seg) = .empty;
if (src.len == 0 or src[0] != '$') return .{ .err = "path must start with $" };
var i: usize = 1;
while (i < src.len) {
const ch = src[i];
if (ch == '.') {
if (i + 1 < src.len and src[i + 1] == '.') {
i += 2;
const m = nameAt(src, i) orelse
return .{ .err = std.fmt.allocPrint(arena, "expected a name after \"..\" at position {d}", .{i}) catch "expected a name after \"..\"" };
segs.append(arena, .{ .descend = m }) catch return oom();
i += m.len;
} else {
i += 1;
if (i < src.len and src[i] == '*') {
segs.append(arena, .wild) catch return oom();
i += 1;
continue;
}
const m = nameAt(src, i) orelse
return .{ .err = std.fmt.allocPrint(arena, "expected a name or * after \".\" at position {d}", .{i}) catch "expected a name or * after \".\"" };
segs.append(arena, .{ .child = m }) catch return oom();
i += m.len;
}
} else if (ch == '[') {
const close = std.mem.indexOfScalarPos(u8, src, i, ']') orelse
return .{ .err = std.fmt.allocPrint(arena, "unclosed [ at position {d}", .{i}) catch "unclosed [" };
const inner = std.mem.trim(u8, src[i + 1 .. close], WS);
i = close + 1;
if (std.mem.eql(u8, inner, "*")) {
segs.append(arena, .wild) catch return oom();
continue;
}
if (intLit(inner)) {
segs.append(arena, .{ .index = parseIntSat(inner) }) catch return oom();
continue;
}
if (sameQuote(inner)) |nm| {
segs.append(arena, .{ .child = nm }) catch return oom();
continue;
}
if (trySlice(inner, arena)) |sl| {
segs.append(arena, sl) catch return oom();
continue;
}
if (std.mem.indexOfScalar(u8, inner, ',') != null) {
var parts: std.ArrayList(Part) = .empty;
var it = std.mem.splitScalar(u8, inner, ',');
while (it.next()) |raw| {
const p = std.mem.trim(u8, raw, WS);
if (intLit(p)) {
parts.append(arena, .{ .index = parseIntSat(p) }) catch return oom();
} else if (unionQuote(p)) |nm| {
parts.append(arena, .{ .child = nm }) catch return oom();
} else {
return .{ .err = std.fmt.allocPrint(arena, "bad union member \"{s}\" in [{s}]", .{ p, inner }) catch "bad union member" };
}
}
segs.append(arena, .{ .union_ = parts.toOwnedSlice(arena) catch return oom() }) catch return oom();
continue;
}
return .{ .err = std.fmt.allocPrint(arena, "unsupported selector [{s}]", .{inner}) catch "unsupported selector" };
} else {
return .{ .err = std.fmt.allocPrint(arena, "unexpected character \"{c}\" at position {d}", .{ ch, i }) catch "unexpected character" };
}
}
return .{ .segs = segs.toOwnedSlice(arena) catch return .{ .err = "out of memory" } };
}
/// Recursive descent: object keys are checked then recursed (TS order).
fn descend(v: Value, p: []const u8, name: []const u8, arena: std.mem.Allocator, out: *std.ArrayList(JPMatch)) void {
switch (v) {
.object => |o| {
var it = o.iterator();
while (it.next()) |e| {
const cp = std.fmt.allocPrint(arena, "{s}.{s}", .{ p, e.key_ptr.* }) catch return;
if (std.mem.eql(u8, e.key_ptr.*, name)) {
out.append(arena, .{ .path = cp, .value = e.value_ptr.* }) catch {};
}
descend(e.value_ptr.*, cp, name, arena, out);
}
},
.array => |a| {
for (a.items, 0..) |item, idx| {
const cp = std.fmt.allocPrint(arena, "{s}[{d}]", .{ p, idx }) catch return;
descend(item, cp, name, arena, out);
}
},
else => {},
}
}
/// Apply one segment to every pending node, appending matches to out.
fn applySeg(nodes: []const JPMatch, seg: Seg, arena: std.mem.Allocator, out: *std.ArrayList(JPMatch)) void {
for (nodes) |nd| {
const v = nd.value;
switch (seg) {
.child => |name| switch (v) {
.object => |o| {
if (o.get(name)) |cv| {
const cp = std.fmt.allocPrint(arena, "{s}.{s}", .{ nd.path, name }) catch return;
out.append(arena, .{ .path = cp, .value = cv }) catch {};
}
},
else => {},
},
.wild => switch (v) {
.array => |a| {
for (a.items, 0..) |item, idx| {
const cp = std.fmt.allocPrint(arena, "{s}[{d}]", .{ nd.path, idx }) catch return;
out.append(arena, .{ .path = cp, .value = item }) catch {};
}
},
.object => |o| {
var it = o.iterator();
while (it.next()) |e| {
const cp = std.fmt.allocPrint(arena, "{s}.{s}", .{ nd.path, e.key_ptr.* }) catch return;
out.append(arena, .{ .path = cp, .value = e.value_ptr.* }) catch {};
}
},
else => {},
},
.descend => |name| descend(v, nd.path, name, arena, out),
.index => |n| switch (v) {
.array => |a| {
const idx = if (n < 0) @as(i64, @intCast(a.items.len)) + n else n;
if (idx >= 0 and idx < @as(i64, @intCast(a.items.len))) {
const cp = std.fmt.allocPrint(arena, "{s}[{d}]", .{ nd.path, idx }) catch return;
out.append(arena, .{ .path = cp, .value = a.items[@intCast(idx)] }) catch {};
}
},
else => {},
},
.slice => |sl| switch (v) {
.array => |a| {
const len: i64 = @intCast(a.items.len);
const start = if (sl.start == null) @as(i64, 0) else if (sl.start.? < 0) @max(len + sl.start.?, 0) else @min(sl.start.?, len);
const end = if (sl.end == null) len else if (sl.end.? < 0) @max(len + sl.end.?, 0) else @min(sl.end.?, len);
var idx = start;
while (idx < end) : (idx += 1) {
const cp = std::fmt.allocPrint(arena, "{s}[{d}]", .{ nd.path, idx }) catch return;
out.append(arena, .{ .path = cp, .value = a.items[@intCast(idx)] }) catch {};
}
},
else => {},
},
.union_ => |parts| {
for (parts) |part| {
const one = [_]JPMatch{nd};
switch (part) {
.index => |n| applySeg(&one, .{ .index = n }, arena, out),
.child => |nm| applySeg(&one, .{ .child = nm }, arena, out),
}
}
},
}
}
}
/// Evaluate a JSONPath expression against a JSON document. All result
/// memory (paths, match slice, parsed tree) lives in the arena.
pub fn queryJsonPath(doc_raw: []const u8, path: []const u8, arena: std.mem.Allocator) JPResult {
if (std.mem.trim(u8, doc_raw, WS).len == 0 or std.mem.trim(u8, path, WS).len == 0) {
return .{ .err = "Both a document and a path are required" };
}
const doc = std.json.parseFromSliceLeaky(Value, arena, doc_raw, .{}) catch {
return .{ .err = "Invalid JSON" };
};
const pr = parsePath(std.mem.trim(u8, path, WS), arena);
if (pr.err != null) return .{ .err = pr.err };
var cur: std.ArrayList(JPMatch) = .empty;
cur.append(arena, .{ .path = "$", .value = doc }) catch return oom();
for (pr.segs) |seg| {
var nxt: std.ArrayList(JPMatch) = .empty;
applySeg(cur.items, seg, arena, &nxt);
cur = nxt;
}
return .{ .matches = cur.toOwnedSlice(arena) catch return oom(), .err = 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 →