Small, feature limited JSONPath (+dialect) implementation.
- Query that returns a single value
- Safe query; returns zero value on failure
- Negative value index; index from the last element, e.g..
foo[-1].bar
- Query that returns multiple values
- Conditional query
- Wildcard
- Descendant node query
- Aggregate functions
- Other functions
Returns the first item in the array.
$.foo.(first).bar
Returns the last item in the array.
$.foo.(last).bar
Returns the length of the array.
$.foo.(length)
package main
import (
"fmt"
"github.com/shellyln/go-small-jsonpath/jsonpath"
)
func main() {
json, err := jsonpath.ReadString(`{"test":[{"abc":1},{"abc":10}]}`)
if err != nil {
fmt.Printf("ReadString: error = %v\n", err)
return
}
path, err := jsonpath.Compile(`$.test[1].abc`)
if err != nil {
fmt.Printf("Compile: error = %v\n", err)
return
}
v, err := path.Query(json) // returns nil, float64, string, []any, map[string]any
if err != nil {
fmt.Printf("Query: error = %v\n", err)
return
}
fmt.Printf("Query: %v\n", v) // float64(10)
vn := path.QueryAsNumberOrZero(json) // returns zero value on failure
fmt.Printf("QueryAsNumberOrZero: %v\n", vn) // float64(10)
vs := path.QueryAsStringOrZero(json) // returns zero value on failure
fmt.Printf("QueryAsStringOrZero: %v\n", vs) // "" (zero value)
}
Data:
{
"foo": [11, 12, 13],
"bar": "abcdefg",
"baz": -9876,
"qux": {
"quux": null
}
}
Queries:
> $.foo[0]
11
> $['foo'][1]
12
> $['foo'][3]
error (index out of range)
> $['foo'][-1]
13
> $["foo"].(length)
3
> $["foo"].(first)
11
> $["foo"].(last)
13
> $.bar
"abcdefg"
> $.bar.(length)
error (unsupported function operand)
> $.qux.quux
nil
> $['qux'].quux
nil
> $['qux']["quux"]
nil
> $.foo
map[string]any{...}
> $.qux
[]any{...}
MIT
Copyright (c) 2023 Shellyl_N and Authors.