Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 27 additions & 11 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,39 @@ jobs:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node-version: [18.x, 20.x, 22.x]
node-version: [24.x]

runs-on: ${{ matrix.os }}

runs-on: ${{ matrix.os }}

steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
- run: npm i
- run: npm run build --if-present
- run: npm run build
- run: npm test

- name: Coveralls
uses: coverallsapp/github-action@main
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
path-to-lcov: ./coverage/lcov.info
build-go:

strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
go-version: ['1.24']

runs-on: ${{ matrix.os }}

defaults:
run:
working-directory: go

steps:
- uses: actions/checkout@v4
- name: Use Go ${{ matrix.go-version }}
uses: actions/setup-go@v5
with:
go-version: ${{ matrix.go-version }}
- run: go build ./...
- run: go test -v ./...
5 changes: 3 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ node_modules

.idea/


trial

test/coverage.html
Expand All @@ -28,4 +27,6 @@ coverage
package-lock.json
yarn.lock


dist
dist-test
*.tsbuildinfo
5 changes: 5 additions & 0 deletions go/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module github.com/jsonicjs/path/go

go 1.24.7

require github.com/jsonicjs/jsonic/go v0.1.4
2 changes: 2 additions & 0 deletions go/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
github.com/jsonicjs/jsonic/go v0.1.4 h1:V1KEzmg/jIwk25+JYj8ig1+B7190rHmH8WqZbT7XlgA=
github.com/jsonicjs/jsonic/go v0.1.4/go.mod h1:ObNKlCG7esWoi4AHCpdgkILvPINV8bpvkbCd4llGGUg=
94 changes: 94 additions & 0 deletions go/path.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/* Copyright (c) 2022-2025 Richard Rodger and other contributors, MIT License */

package path

import (
jsonic "github.com/jsonicjs/jsonic/go"
)

type PathOptions struct{}

// Path is a Jsonic plugin that tracks the property path to the current
// location during parsing. The path is stored in Rule.K["path"] as a
// []any slice of string keys and int indices.
func Path(j *jsonic.Jsonic, opts map[string]any) {

j.Rule("val", func(rs *jsonic.RuleSpec) {
rs.BO = append(rs.BO, func(r *jsonic.Rule, ctx *jsonic.Context) {
if r.D == 0 {
var base []any
if ctx.Meta != nil {
if pm, ok := ctx.Meta["path"].(map[string]any); ok {
if b, ok := pm["base"].([]any); ok {
base = make([]any, len(b))
copy(base, b)
}
}
}
if base == nil {
base = []any{}
}
r.K["path"] = base
}
})
})

j.Rule("map", func(rs *jsonic.RuleSpec) {
rs.BO = append(rs.BO, func(r *jsonic.Rule, ctx *jsonic.Context) {
delete(r.K, "index")
})
})

j.Rule("pair", func(rs *jsonic.RuleSpec) {
rs.AO = append(rs.AO, func(r *jsonic.Rule, ctx *jsonic.Context) {
if r.D > 0 && r.U["pair"] != nil {
key := r.U["key"]
parentPath := toPathSlice(r.K["path"])
childPath := make([]any, len(parentPath)+1)
copy(childPath, parentPath)
childPath[len(parentPath)] = key
r.Child.K["path"] = childPath
r.Child.K["key"] = key
}
})
})

j.Rule("list", func(rs *jsonic.RuleSpec) {
rs.BO = append(rs.BO, func(r *jsonic.Rule, ctx *jsonic.Context) {
r.K["index"] = -1
})
})

j.Rule("elem", func(rs *jsonic.RuleSpec) {
rs.AO = append(rs.AO, func(r *jsonic.Rule, ctx *jsonic.Context) {
if r.D > 0 {
idx := 0
if v, ok := r.K["index"].(int); ok {
idx = v + 1
}
r.K["index"] = idx
parentPath := toPathSlice(r.K["path"])
childPath := make([]any, len(parentPath)+1)
copy(childPath, parentPath)
childPath[len(parentPath)] = idx
r.Child.K["path"] = childPath
r.Child.K["key"] = idx
r.Child.K["index"] = idx
}
})
})
}

// MakeJsonic creates a Jsonic parser instance with the Path plugin.
func MakeJsonic() *jsonic.Jsonic {
j := jsonic.Make()
j.Use(Path, nil)
return j
}

func toPathSlice(v any) []any {
if p, ok := v.([]any); ok {
return p
}
return []any{}
}
212 changes: 212 additions & 0 deletions go/path_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
/* Copyright (c) 2022-2025 Richard Rodger and other contributors, MIT License */

package path

import (
"fmt"
"reflect"
"strings"
"testing"

jsonic "github.com/jsonicjs/jsonic/go"
)

func assert(t *testing.T, name string, got, want any) {
t.Helper()
if !reflect.DeepEqual(got, want) {
t.Errorf("%s:\n got: %#v\n want: %#v", name, got, want)
}
}

// addPathCapture adds a val AC callback that annotates nodes with path info.
func addPathCapture(j *jsonic.Jsonic) {
j.Rule("val", func(rs *jsonic.RuleSpec) {
rs.AC = append(rs.AC, func(r *jsonic.Rule, ctx *jsonic.Context) {
path := toPathSlice(r.K["path"])
switch node := r.Node.(type) {
case map[string]any:
node["$"] = fmtPath(path)
case []any:
// Leave arrays as-is; elements are already annotated.
default:
r.Node = fmtValPath(r.Node, path)
}
})
})
}

func TestHappy(t *testing.T) {
j := MakeJsonic()
result, err := j.Parse("{a:{b:1,c:[2,3]}}")
if err != nil {
t.Fatal(err)
}
m := result.(map[string]any)
a := m["a"].(map[string]any)
assert(t, "b", a["b"], float64(1))
}

func TestPathTracking(t *testing.T) {
j := jsonic.Make()
j.Use(Path, nil)
addPathCapture(j)

result, err := j.Parse("{a:{b:1}}")
if err != nil {
t.Fatal(err)
}

m := result.(map[string]any)
assert(t, "root-path", m["$"], "<>")

a := m["a"].(map[string]any)
assert(t, "a-path", a["$"], "<a>")
assert(t, "b-val", a["b"], "<1:a,b>")
}

func TestMetaBasePath(t *testing.T) {
j := jsonic.Make()
j.Use(Path, nil)

j.Rule("val", func(rs *jsonic.RuleSpec) {
rs.AC = append(rs.AC, func(r *jsonic.Rule, ctx *jsonic.Context) {
path := toPathSlice(r.K["path"])
if node, ok := r.Node.(map[string]any); ok {
node["$"] = fmtPath(path)
}
})
})

result, err := j.ParseMeta("{a:1}", map[string]any{
"path": map[string]any{
"base": []any{"x", "y"},
},
})
if err != nil {
t.Fatal(err)
}

m := result.(map[string]any)
assert(t, "root", m["$"], "<x,y>")
}

func TestObjectPaths(t *testing.T) {
j := jsonic.Make()
j.Use(Path, nil)
addPathCapture(j)

result, err := j.Parse("{a:1}")
if err != nil {
t.Fatal(err)
}
m := result.(map[string]any)
assert(t, "root", m["$"], "<>")
assert(t, "a", m["a"], "<1:a>")

result, err = j.Parse("{a:1,b:B}")
if err != nil {
t.Fatal(err)
}
m = result.(map[string]any)
assert(t, "root2", m["$"], "<>")
assert(t, "a2", m["a"], "<1:a>")
assert(t, "b2", m["b"], "<B:b>")
}

func TestNestedObjectPaths(t *testing.T) {
j := jsonic.Make()
j.Use(Path, nil)
addPathCapture(j)

result, err := j.Parse("{x:{a:1}}")
if err != nil {
t.Fatal(err)
}
m := result.(map[string]any)
assert(t, "root", m["$"], "<>")
x := m["x"].(map[string]any)
assert(t, "x", x["$"], "<x>")
assert(t, "x-a", x["a"], "<1:x,a>")
}

func TestArrayPaths(t *testing.T) {
j := jsonic.Make()
j.Use(Path, nil)
addPathCapture(j)

result, err := j.Parse("[1,2,3]")
if err != nil {
t.Fatal(err)
}

arr, ok := result.([]any)
if !ok {
t.Fatalf("expected []any, got %T", result)
}
assert(t, "elem-0", arr[0], "<1:0>")
assert(t, "elem-1", arr[1], "<2:1>")
assert(t, "elem-2", arr[2], "<3:2>")
}

func TestMakeJsonic(t *testing.T) {
j := MakeJsonic()
result, err := j.Parse("{a:1}")
if err != nil {
t.Fatal(err)
}
m, ok := result.(map[string]any)
if !ok {
t.Fatalf("expected map, got %T", result)
}
assert(t, "a", m["a"], float64(1))
}

// fmtPath formats a path slice as "<a,b,c>".
func fmtPath(path []any) string {
parts := make([]string, len(path))
for i, p := range path {
parts[i] = fmtKey(p)
}
return "<" + strings.Join(parts, ",") + ">"
}

// fmtValPath formats a value with its path as "<value:a,b>".
func fmtValPath(val any, path []any) string {
parts := make([]string, len(path))
for i, p := range path {
parts[i] = fmtKey(p)
}
return "<" + fmtVal(val) + ":" + strings.Join(parts, ",") + ">"
}

func fmtKey(v any) string {
switch k := v.(type) {
case string:
return k
case int:
return fmt.Sprintf("%d", k)
case float64:
if k == float64(int64(k)) {
return fmt.Sprintf("%d", int64(k))
}
return fmt.Sprintf("%g", k)
default:
return fmt.Sprintf("%v", v)
}
}

func fmtVal(v any) string {
switch val := v.(type) {
case string:
return val
case float64:
if val == float64(int64(val)) {
return fmt.Sprintf("%d", int64(val))
}
return fmt.Sprintf("%g", val)
case bool:
return fmt.Sprintf("%t", val)
default:
return fmt.Sprintf("%v", v)
}
}
9 changes: 0 additions & 9 deletions jest.config.js

This file was deleted.

Loading
Loading