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). Core grammar over
// System.Text.Json: $ root, .name / ["name"] child, [*] / .* wildcard,
// ..name recursive descent, [n] index (negative from end), [a:b] slice,
// [a,b] union. Missing paths yield empty results, never errors.
using System.Text.Json;
using System.Text.RegularExpressions;

var doc = JsonDocument.Parse(args.Length > 0 ? args[0] : Console.In.ReadToEnd());
var path = args.Length > 1 ? args[1] : throw new ArgumentException("usage: jsonpath <json> <path>");

var segs = ParsePath(path);
var current = new List<(string Path, JsonElement Value)> { ("$", doc.RootElement) };
foreach (var seg in segs)
{
    var next = new List<(string, JsonElement)>();
    foreach (var node in current) ApplySeg(node, seg, next);
    current = next;
}
foreach (var (p, v) in current)
    Console.WriteLine($"{p} = {JsonSerializer.Serialize(v, new JsonSerializerOptions { WriteIndented = false })}");

List<object> ParsePath(string src)
{
    if (!src.StartsWith('$')) throw new ArgumentException("path must start with $");
    var segs = new List<object>();
    int i = 1;
    while (i < src.Length)
    {
        if (src[i] == '.')
        {
            if (i + 1 < src.Length && src[i + 1] == '.') // recursive descent
            {
                var m = Regex.Match(src[(i + 2)..], "^[A-Za-z_][\\w-]*");
                if (!m.Success) throw new ArgumentException($"expected a name after \"..\" at position {i}");
                segs.Add(new Descend(m.Value));
                i += 2 + m.Value.Length;
            }
            else
            {
                i += 1;
                if (i < src.Length && src[i] == '*') { segs.Add(new Wild()); i += 1; continue; }
                var m = Regex.Match(src[i..], "^[A-Za-z_][\\w-]*");
                if (!m.Success) throw new ArgumentException($"expected a name or * after \".\" at position {i}");
                segs.Add(new Child(m.Value));
                i += m.Value.Length;
            }
        }
        else if (src[i] == '[')
        {
            int close = src.IndexOf(']', i);
            if (close == -1) throw new ArgumentException($"unclosed [ at position {i}");
            string inner = src[(i + 1)..close].Trim();
            i = close + 1;
            if (inner == "*") { segs.Add(new Wild()); continue; }
            if (Regex.IsMatch(inner, "^-?\\d+$")) { segs.Add(new Index(int.Parse(inner))); continue; }
            var q = Regex.Match(inner, "^['\"]([^'\"]*)['\"]$");
            if (q.Success) { segs.Add(new Child(q.Groups[1].Value)); continue; }
            var slice = Regex.Match(inner, "^(-?\\d+)?\\s*:\\s*(-?\\d+)?$");
            if (slice.Success)
            {
                segs.Add(new Slice(
                    slice.Groups[1].Value.Length > 0 ? int.Parse(slice.Groups[1].Value) : (int?)null,
                    slice.Groups[2].Value.Length > 0 ? int.Parse(slice.Groups[2].Value) : (int?)null));
                continue;
            }
            throw new ArgumentException($"unsupported selector [{inner}]");
        }
        else throw new ArgumentException($"unexpected character \"{src[i]}\" at position {i}");
    }
    return segs;
}

void ApplySeg((string Path, JsonElement Value) node, object seg, List<(string, JsonElement)> output)
{
    var v = node.Value;
    switch (seg)
    {
        case Child c:
            if (v.ValueKind == JsonValueKind.Object && v.TryGetProperty(c.Name, out var child))
                output.Add(($"{node.Path}.{c.Name}", child));
            break;
        case Wild:
            if (v.ValueKind == JsonValueKind.Array)
                for (int k = 0; k < v.GetArrayLength(); k++) output.Add(($"{node.Path}[{k}]", v[k]));
            else if (v.ValueKind == JsonValueKind.Object)
                foreach (var prop in v.EnumerateObject()) output.Add(($"{node.Path}.{prop.Name}", prop.Value));
            break;
        case Descend d:
            void Visit(JsonElement val, string p)
            {
                if (val.ValueKind == JsonValueKind.Object)
                    foreach (var prop in val.EnumerateObject())
                    {
                        if (prop.Name == d.Name) output.Add(($"{p}.{prop.Name}", prop.Value));
                        Visit(prop.Value, $"{p}.{prop.Name}");
                    }
                else if (val.ValueKind == JsonValueKind.Array)
                    for (int k = 0; k < val.GetArrayLength(); k++) Visit(val[k], $"{p}[{k}]");
            }
            Visit(v, node.Path);
            break;
        case Index idx:
            if (v.ValueKind == JsonValueKind.Array)
            {
                int len = v.GetArrayLength();
                int real = idx.N < 0 ? len + idx.N : idx.N;
                if (real >= 0 && real < len) output.Add(($"{node.Path}[{real}]", v[real]));
            }
            break;
        case Slice sl:
            if (v.ValueKind == JsonValueKind.Array)
            {
                int len = v.GetArrayLength();
                int start = sl.Start ?? 0;
                int end = sl.End ?? len;
                if (start < 0) start = Math.Max(len + start, 0);
                if (end < 0) end = Math.Max(len + end, 0);
                for (int k = Math.Min(start, len); k < Math.Min(end, len); k++)
                    output.Add(($"{node.Path}[{k}]", v[k]));
            }
            break;
    }
}

record Child(string Name);
record Wild;
record Descend(string Name);
record Index(int N);
record Slice(int? Start, int? End);

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 →