This is a Go implementation of JSONPath introduced in:
https://goessner.net/articles/JsonPath/
as well as JSON path expressions of the form:
/key1/index/*/key2
with the following exceptions:
-
If a path component is a it should be a valid identifier or number. If that is not the case, it should be a string literal, that is, quoted.
For example:
$.dash-key
is invalid. You must quote it:$."dash-key"
or$.'dash-key'
. -
Function and method calls must have a possibly empty argument list.
For example:
length(@)
and@.length()
are valid, but@.length
will look for alength
key under the current node. -
Decimals cannot start with a period, that is
.5
is invalid. Use0.5
instead. Decimal starting with a period confuses the lexer. -
Regular expressions are not supported yet.
First, compile the path:
path, err:= gojsonpath.Parse("$.store.book[*].author")
Then you can use:
results, err:= gojsonpath.Find(doc,path)
or you can capture the full-path for the nodes that match:
result:=make([]any,0)
err := gojsonpath.Search(doc,path,func(elem []gojsonpath.Element) {
result=append(result,elem[len(elem)-1].Node)
})
You can use the simple path parser to compile '/' separated paths:
path, err := gojsonpath.Parse("/store/book/*/author")
Simple paths must start with '/', and may contain object keys, array indexes, or '*' to match anything, separated by '/'.
This implementation of JSONPath works with a flexible document
model. To use the familiar map[string]any
implementation of JSON,
use:
var jsonDoc any
json.Unmarshal(jsonBytes,&jsonDoc)
doc := gojsonpath.MapModel{Doc:jsonDoc}
The DocModel
interface provides a view of the underlying model, so
the JSON document does not have to be a map[string]any
. Any
hierarchical document model supporting key-value, array, and value
nodes can be used.