Skip to content

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

# frozen_string_literal: true

# jsonpath — JSONPath query engine. Ruby port (canonical TS:
# src/lib/jsonpath.ts; Go twin: cli/jsonpath). Tokenizes a core-grammar path
# — "$" root, ".name" / "['name']" child, ".*" / "[*]" wildcard, "..name"
# recursive descent, "[n]" index (negative = from end), "[start:end]" slice,
# "[a,b]" union of indexes and quoted names — and matches it over a parsed
# document. Ruby hashes keep JSON key insertion order, so wildcard/descent
# match order matches the TS contract; path errors are byte-for-byte the TS
# texts; parse failures surface the parser's message. Filter [?()] and
# script expressions are unsupported by design. Stdlib only (json).
# Segments are tagged arrays: [:child, name], [:wild], [:descend, name],
# [:index, n], [:slice, start, end], [:union, parts].

require 'json'

NAME = /[A-Za-z_][A-Za-z0-9_-]*/.freeze
INT = /\A-?\d+\z/.freeze
SLICE = /\A(-?\d+)?\s*:\s*(-?\d+)?\z/.freeze
SAME_QUOTE = [/\A'[^']*'\z/, /\A"[^"]*"\z/].freeze
UNION_QUOTE = /\A['"][^'"]*['"]\z/.freeze

def int_or_nil(side)
  side && !side.empty? ? side.to_i : nil
end

# '...' or "..." with the SAME quotes and none inside (bracket child form).
def same_quote(t)
  return nil if t.length < 2
  q = t[0]
  return nil unless q == "'" || q == '"'
  return nil unless t[-1] == q
  return nil unless t.index(q, 1) == t.length - 1
  t[1..-2]
end

# Any quote ... any quote with no quotes inside (union member form).
def union_quote(t)
  return nil if t.length < 2
  return nil unless t[0] == "'" || t[0] == '"'
  return nil unless t[-1] == "'" || t[-1] == '"'
  mid = t[1..-2]
  return nil if mid.include?("'") || mid.include?('"')
  mid
end

# Tokenize+parse a path into segments; returns [segments, nil] or [nil, error].
def parse_path(src)
  segs = []
  return [nil, 'path must start with $'] unless src[0] == '$'
  i = 1
  while i < src.length
    ch = src[i]
    if ch == '.'
      if src[i + 1] == '.'
        i += 2
        m = NAME.match(src, i)
        return [nil, %(expected a name after ".." at position #{i})] unless m
        segs << [:descend, m[0]]
        i = m.end(0)
      else
        i += 1
        if src[i] == '*'
          segs << [:wild]
          i += 1
          next
        end
        m = NAME.match(src, i)
        return [nil, %(expected a name or * after "." at position #{i})] unless m
        segs << [:child, m[0]]
        i = m.end(0)
      end
    elsif ch == '['
      close = src.index(']', i)
      return [nil, "unclosed [ at position #{i}"] unless close
      inner = src[(i + 1)...close].strip
      i = close + 1
      if inner == '*'
        segs << [:wild]
      elsif INT.match?(inner)
        segs << [:index, inner.to_i]
      elsif (nm = same_quote(inner))
        segs << [:child, nm]
      elsif (sl = SLICE.match(inner))
        segs << [:slice, int_or_nil(sl[1]), int_or_nil(sl[2])]
      elsif inner.include?(',')
        parts = []
        inner.split(',').each do |raw|
          p = raw.strip
          if INT.match?(p)
            parts << [:index, p.to_i]
          elsif (nm = union_quote(p))
            parts << [:child, nm]
          else
            return [nil, "bad union member \"#{p}\" in [#{inner}]"]
          end
        end
        segs << [:union, parts]
      else
        return [nil, "unsupported selector [#{inner}]"]
      end
    else
      return [nil, "unexpected character \"#{ch}\" at position #{i}"]
    end
  end
  [segs, nil]
end

# Recursive descent: object keys are checked then recursed (TS order).
def descend_visit(val, path, name, out)
  if val.is_a?(Hash)
    val.each do |key, child|
      cp = "#{path}.#{key}"
      out << { path: cp, value: child } if key == name
      descend_visit(child, cp, name, out)
    end
  elsif val.is_a?(Array)
    val.each_with_index { |item, idx| descend_visit(item, "#{path}[#{idx}]", name, out) }
  end
end

# Apply one segment to every pending node, appending matches to out.
def apply_seg(nodes, seg, out)
  nodes.each do |node|
    path = node[:path]
    v = node[:value]
    case seg[0]
    when :child
      if v.is_a?(Hash) && v.key?(seg[1])
        out << { path: "#{path}.#{seg[1]}", value: v[seg[1]] }
      end
    when :wild
      if v.is_a?(Array)
        v.each_with_index { |item, idx| out << { path: "#{path}[#{idx}]", value: item } }
      elsif v.is_a?(Hash)
        v.each { |key, val| out << { path: "#{path}.#{key}", value: val } }
      end
    when :descend
      descend_visit(v, path, seg[1], out)
    when :index
      if v.is_a?(Array)
        idx = seg[1].negative? ? v.length + seg[1] : seg[1]
        out << { path: "#{path}[#{idx}]", value: v[idx] } if idx >= 0 && idx < v.length
      end
    when :slice
      if v.is_a?(Array)
        len = v.length
        start = seg[1].nil? ? 0 : seg[1].negative? ? [(len + seg[1]), 0].max : [seg[1], len].min
        fin = seg[2].nil? ? len : seg[2].negative? ? [(len + seg[2]), 0].max : [seg[2], len].min
        (start...fin).each { |idx| out << { path: "#{path}[#{idx}]", value: v[idx] } }
      end
    end
  end
end

# Evaluate a JSONPath expression against a JSON document.
def query_json_path(doc_raw, path)
  if doc_raw.strip.empty? || path.strip.empty?
    return { matches: [], error: 'Both a document and a path are required' }
  end
  begin
    doc = JSON.parse(doc_raw)
  rescue JSON::ParserError => e
    return { matches: [], error: e.message }
  end
  segs, err = parse_path(path.strip)
  return { matches: [], error: err } if err
  current = [{ path: '$', value: doc }]
  segs.each do |seg|
    nxt = []
    if seg[0] == :union
      current.each { |node| seg[1].each { |part| apply_seg([node], part, nxt) } }
    else
      apply_seg(current, seg, nxt)
    end
    current = nxt
  end
  { matches: current, error: nil }
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 →