Skip to content

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

// Package jsonpath is the Go twin of CosmoDev's src/lib/jsonpath.ts (dual
// source: the web lib is TypeScript, the CLI lib is Go — kept in lock-step).
// Pure + deterministic, never panics. The table-driven tests in
// jsonpath_test.go share vectors with src/lib/jsonpath.test.ts so the two
// implementations are held to the same contract.
//
// Grammar (mirrors the TS lib exactly): "$" root, ".name" and "['name']"
// child access, "[*]" and ".*" wildcard, "..name" recursive descent, "[n]"
// index (negative = from the end), "[start:end]" slice, and "[a,b]" union.
// Filter expressions [?()], script expressions, and regex filters are
// unsupported by design, as in the TS lib; the error texts produced by
// parsePath are part of the shared contract and are reproduced byte-for-byte.
//
// Documents are decoded into an insertion-ordered object type: JS objects
// enumerate keys in insertion order and the ORDER of matches (wildcards,
// recursive descent) is part of the contract, so encoding/json's map
// decoding cannot be used.
package jsonpath

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"math"
	"regexp"
	"strconv"
	"strings"
	"unicode/utf8"
)

// Json is a parsed JSON value: nil (JSON null), bool, float64, string,
// []Json, or *JsonObject.
type Json any

// JsonObject is a JSON object that remembers key insertion order, matching
// JS object enumeration semantics. A duplicate key keeps its original
// position and the later value wins — exactly like re-assigning an existing
// property in JavaScript.
type JsonObject struct {
	keys []string
	vals map[string]Json
}

func newJSONObject() *JsonObject {
	return &JsonObject{vals: make(map[string]Json)}
}

func (o *JsonObject) set(key string, v Json) {
	if _, dup := o.vals[key]; !dup {
		o.keys = append(o.keys, key)
	}
	o.vals[key] = v
}

func (o *JsonObject) has(key string) bool {
	_, ok := o.vals[key]
	return ok
}

func (o *JsonObject) get(key string) Json {
	return o.vals[key]
}

// keyOrder returns the keys in insertion order (the TS Object.keys order).
func (o *JsonObject) keyOrder() []string {
	return o.keys
}

// Match is one query result: the "$"-rooted path of the match (for example
// $.store.book[1].title) and its value. Go twin of the TS JsonPathMatch.
type Match struct {
	Path  string
	Value Json
}

// Result mirrors the TS JsonPathResult union: either Matches with an empty
// Error (the TS error: null), or empty Matches with Error set.
type Result struct {
	Matches []Match
	Error   string
}

// segKind discriminates the segment union (the TS Seg type).
type segKind int

const (
	segChild segKind = iota
	segWild
	segDescend
	segIndex
	segSlice
	segUnion
)

// unionPart is one member of an [a,b] union: an index or a quoted name.
type unionPart struct {
	index bool // true → n (index member); false → name (quoted child member)
	n     int
	name  string
}

// asSeg lifts a union member into the single-segment form applySeg consumes.
func (p unionPart) asSeg() seg {
	if p.index {
		return seg{k: segIndex, n: p.n}
	}
	return seg{k: segChild, name: p.name}
}

// seg is one parsed segment of the path (the TS Seg union flattened into a
// tagged struct).
type seg struct {
	k     segKind
	name  string // child / descend
	n     int    // index
	start *int   // slice start: nil = open (TS null)
	end   *int   // slice end: nil = open (TS null)
	parts []unionPart
}

var (
	nameRe     = regexp.MustCompile(`^[A-Za-z_][\w-]*`)
	intRe      = regexp.MustCompile(`^-?\d+$`)
	singleQuot = regexp.MustCompile(`^'([^']*)'$`)
	doubleQuot = regexp.MustCompile(`^"([^"]*)"$`)
	quotedRe   = regexp.MustCompile(`^['"]([^'"]*)['"]$`)
	sliceRe    = regexp.MustCompile(`^(-?\d+)?\s*:\s*(-?\d+)?$`)
)

// parsePathInt mirrors the TS Number() on an integer-only string. Magnitudes
// beyond int64 overflow Atoi, so they clamp to the int extremes: TS numbers
// are floats and such an index can never land inside a real array, so
// clamping behaves identically in the slice/index arithmetic.
func parsePathInt(s string) int {
	if n, err := strconv.Atoi(s); err == nil {
		return n
	}
	if strings.HasPrefix(s, "-") {
		return math.MinInt
	}
	return math.MaxInt
}

// runeAt returns the rune starting at byte offset i, for error messages
// (the TS code slices the single character at src[i]).
func runeAt(s string, i int) string {
	_, size := utf8.DecodeRuneInString(s[i:])
	return s[i : i+size]
}

// parsePath tokenizes+parses a path into segments. On bad syntax it returns
// nil and the exact TS error string.
func parsePath(src string) ([]seg, string) {
	segs := []seg{}
	i := 0
	if len(src) == 0 || src[0] != '$' {
		return nil, "path must start with $"
	}
	i = 1
	for i < len(src) {
		ch := src[i]
		switch ch {
		case '.':
			if i+1 < len(src) && src[i+1] == '.' {
				i += 2
				m := nameRe.FindString(src[i:])
				if m == "" {
					return nil, fmt.Sprintf("expected a name after \"..\" at position %d", i)
				}
				segs = append(segs, seg{k: segDescend, name: m})
				i += len(m)
			} else {
				i++
				if i < len(src) && src[i] == '*' {
					segs = append(segs, seg{k: segWild})
					i++
					continue
				}
				m := nameRe.FindString(src[i:])
				if m == "" {
					return nil, fmt.Sprintf("expected a name or * after \".\" at position %d", i)
				}
				segs = append(segs, seg{k: segChild, name: m})
				i += len(m)
			}
		case '[':
			rel := strings.IndexByte(src[i:], ']')
			if rel == -1 {
				return nil, fmt.Sprintf("unclosed [ at position %d", i)
			}
			closeIdx := i + rel
			inner := strings.TrimSpace(src[i+1 : closeIdx])
			i = closeIdx + 1
			switch {
			case inner == "*":
				segs = append(segs, seg{k: segWild})
			case intRe.MatchString(inner):
				segs = append(segs, seg{k: segIndex, n: parsePathInt(inner)})
			case singleQuot.MatchString(inner) || doubleQuot.MatchString(inner):
				segs = append(segs, seg{k: segChild, name: quotedRe.FindStringSubmatch(inner)[1]})
			case sliceRe.MatchString(inner):
				m := sliceRe.FindStringSubmatch(inner)
				sg := seg{k: segSlice}
				if m[1] != "" {
					n := parsePathInt(m[1])
					sg.start = &n
				}
				if m[2] != "" {
					n := parsePathInt(m[2])
					sg.end = &n
				}
				segs = append(segs, sg)
			case strings.Contains(inner, ","):
				parts := []unionPart{}
				for _, raw := range strings.Split(inner, ",") {
					p := strings.TrimSpace(raw)
					switch {
					case intRe.MatchString(p):
						parts = append(parts, unionPart{index: true, n: parsePathInt(p)})
					case quotedRe.MatchString(p):
						parts = append(parts, unionPart{name: p[1 : len(p)-1]})
					default:
						return nil, fmt.Sprintf("bad union member \"%s\" in [%s]", p, inner)
					}
				}
				segs = append(segs, seg{k: segUnion, parts: parts})
			default:
				return nil, fmt.Sprintf("unsupported selector [%s]", inner)
			}
		default:
			return nil, fmt.Sprintf("unexpected character \"%s\" at position %d", runeAt(src, i), i)
		}
	}
	return segs, ""
}

// keyPath joins a parent path with a child key (the TS keyPath).
func keyPath(parent, key string) string {
	return parent + "." + key
}

// applySeg applies one segment to every node, appending results to out
// (mirrors applySeg in the TS lib; union is handled by the caller).
func applySeg(nodes []Match, sg seg, out []Match) []Match {
	for _, node := range nodes {
		v := node.Value
		switch sg.k {
		case segChild:
			if obj, ok := v.(*JsonObject); ok && obj.has(sg.name) {
				out = append(out, Match{Path: keyPath(node.Path, sg.name), Value: obj.get(sg.name)})
			}
		case segWild:
			if arr, ok := v.([]Json); ok {
				for idx, item := range arr {
					out = append(out, Match{Path: fmt.Sprintf("%s[%d]", node.Path, idx), Value: item})
				}
			} else if obj, ok := v.(*JsonObject); ok {
				for _, key := range obj.keyOrder() {
					out = append(out, Match{Path: keyPath(node.Path, key), Value: obj.get(key)})
				}
			}
		case segDescend:
			out = descendVisit(v, node.Path, sg.name, out)
		case segIndex:
			if arr, ok := v.([]Json); ok {
				idx := sg.n
				if idx < 0 {
					idx += len(arr)
				}
				if idx >= 0 && idx < len(arr) {
					out = append(out, Match{Path: fmt.Sprintf("%s[%d]", node.Path, idx), Value: arr[idx]})
				}
			}
		case segSlice:
			if arr, ok := v.([]Json); ok {
				ln := len(arr)
				start := 0
				if sg.start != nil {
					if *sg.start < 0 {
						start = ln + *sg.start
						if start < 0 {
							start = 0
						}
					} else {
						start = *sg.start
						if start > ln {
							start = ln
						}
					}
				}
				end := ln
				if sg.end != nil {
					if *sg.end < 0 {
						end = ln + *sg.end
						if end < 0 {
							end = 0
						}
					} else {
						end = *sg.end
						if end > ln {
							end = ln
						}
					}
				}
				for idx := start; idx < end; idx++ {
					out = append(out, Match{Path: fmt.Sprintf("%s[%d]", node.Path, idx), Value: arr[idx]})
				}
			}
		}
	}
	return out
}

// descendVisit is the TS recursive-descent visit(): on objects, matching
// keys are emitted and every child is then visited; arrays are walked.
func descendVisit(val Json, path, name string, out []Match) []Match {
	switch t := val.(type) {
	case *JsonObject:
		for _, key := range t.keyOrder() {
			child := t.get(key)
			if key == name {
				out = append(out, Match{Path: keyPath(path, key), Value: child})
			}
			out = descendVisit(child, keyPath(path, key), name, out)
		}
	case []Json:
		for idx, item := range t {
			out = descendVisit(item, fmt.Sprintf("%s[%d]", path, idx), name, out)
		}
	}
	return out
}

// parseJSONDocument decodes raw into Json with insertion-ordered objects and
// rejects trailing data, mirroring JSON.parse (which throws on both).
func parseJSONDocument(raw string) (Json, error) {
	dec := json.NewDecoder(strings.NewReader(raw))
	v, err := decodeValue(dec)
	if err != nil {
		return nil, err
	}
	if _, err := dec.Token(); err != io.EOF {
		if err != nil {
			return nil, err
		}
		return nil, errors.New("unexpected trailing data after the JSON document")
	}
	return v, nil
}

// decodeValue reads the next complete JSON value from the token stream.
func decodeValue(dec *json.Decoder) (Json, error) {
	tok, err := dec.Token()
	if err != nil {
		return nil, err
	}
	return decodeFromToken(dec, tok)
}

// decodeFromToken completes a value whose opening token has been consumed.
func decodeFromToken(dec *json.Decoder, tok json.Token) (Json, error) {
	if d, ok := tok.(json.Delim); ok {
		switch d {
		case '{':
			obj := newJSONObject()
			for dec.More() {
				keyTok, err := dec.Token()
				if err != nil {
					return nil, err
				}
				key, ok := keyTok.(string)
				if !ok {
					return nil, fmt.Errorf("unexpected object key token %v", keyTok)
				}
				val, err := decodeValue(dec)
				if err != nil {
					return nil, err
				}
				obj.set(key, val)
			}
			if _, err := dec.Token(); err != nil { // consume '}'
				return nil, err
			}
			return obj, nil
		case '[':
			arr := []Json{}
			for dec.More() {
				val, err := decodeValue(dec)
				if err != nil {
					return nil, err
				}
				arr = append(arr, val)
			}
			if _, err := dec.Token(); err != nil { // consume ']'
				return nil, err
			}
			return arr, nil
		default:
			return nil, fmt.Errorf("unexpected delimiter %v", d)
		}
	}
	return tok, nil
}

// QueryJsonPath evaluates a JSONPath expression against a JSON document.
// It is the Go twin of queryJsonPath() in src/lib/jsonpath.ts and must
// agree with it on every shared vector.
func QueryJsonPath(docRaw, path string) Result {
	if strings.TrimSpace(docRaw) == "" || strings.TrimSpace(path) == "" {
		return Result{Matches: []Match{}, Error: "Both a document and a path are required"}
	}
	doc, err := parseJSONDocument(docRaw)
	if err != nil {
		// TS: e instanceof Error ? e.message : 'Invalid JSON'. Every Go decode
		// failure is a real error value, so the TS 'Invalid JSON' fallback is
		// unreachable here by construction.
		return Result{Matches: []Match{}, Error: err.Error()}
	}
	segs, errStr := parsePath(strings.TrimSpace(path))
	if errStr != "" {
		return Result{Matches: []Match{}, Error: errStr}
	}
	current := []Match{{Path: "$", Value: doc}}
	for _, sg := range segs {
		next := []Match{}
		// Unions collect their members per node, in member order.
		if sg.k == segUnion {
			for _, node := range current {
				for _, part := range sg.parts {
					next = applySeg([]Match{node}, part.asSeg(), next)
				}
			}
		} else {
			next = applySeg(current, sg, next)
		}
		current = next
	}
	return Result{Matches: current, Error: ""}
}

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 →