Documentation
¶
Overview ¶
Package jsonpath implements RFC 9535 JSONPath queries for Go values.
Index ¶
- Variables
- func Valid(expr string) bool
- type FuncType
- type Function
- type FunctionValue
- type IndexElement
- type LocatedNode
- type LocatedNodeList
- type Logical
- type NameElement
- type NodeList
- type Nodes
- type NormalizedPath
- func (p NormalizedPath) Append(elem PathElement) (NormalizedPath, error)
- func (p NormalizedPath) Compare(q NormalizedPath) int
- func (p NormalizedPath) Element(i int) PathElement
- func (p NormalizedPath) Elements() []PathElement
- func (p NormalizedPath) Equal(q NormalizedPath) bool
- func (p NormalizedPath) Len() int
- func (p NormalizedPath) MarshalText() ([]byte, error)
- func (p NormalizedPath) Pointer() string
- func (p NormalizedPath) String() string
- type Option
- type ParseError
- type Parser
- type Path
- type PathElement
- type Value
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrPathParse is returned when a JSONPath expression cannot be parsed. ErrPathParse = errors.New("jsonpath: parse error") // ErrFunction is returned for function registration or expression failures. ErrFunction = errors.New("jsonpath: function error") // ErrUnmarshal is returned when JSON unmarshaling fails in QueryJSON functions. ErrUnmarshal = errors.New("jsonpath: unmarshal error") // ErrInvalidPath is returned for an invalid compiled or normalized path. ErrInvalidPath = errors.New("jsonpath: invalid path") )
Functions ¶
Types ¶
type FuncType ¶
type FuncType uint8
FuncType describes a function extension's parameter or result type as defined by RFC 9535 §2.4.1.
type Function ¶
type Function struct {
// contains filtered or unexported fields
}
Function is an immutable extension function definition created by NewValueFunction, NewLogicalFunction, or NewNodesFunction. Callbacks must be safe for concurrent use when the configured Parser is used concurrently.
func NewLogicalFunction ¶ added in v0.1.17
func NewLogicalFunction(name string, params []FuncType, call func([]FunctionValue) Logical) Function
NewLogicalFunction defines a function that returns a logical value.
func NewNodesFunction ¶ added in v0.1.17
func NewNodesFunction(name string, params []FuncType, call func([]FunctionValue) Nodes) Function
NewNodesFunction defines a function that returns a node list.
func NewValueFunction ¶ added in v0.1.17
func NewValueFunction(name string, params []FuncType, call func([]FunctionValue) Value) Function
NewValueFunction defines a function that returns a JSON value.
type FunctionValue ¶ added in v0.1.16
type FunctionValue = ast.FunctionValue
FunctionValue is one of the RFC 9535 function runtime value types.
type LocatedNode ¶
type LocatedNode struct {
Value any // Value is the selected JSON value.
Path NormalizedPath // Path is the normalized path to Value.
}
LocatedNode pairs a value with the NormalizedPath for its location within a JSON query argument.
type LocatedNodeList ¶
type LocatedNodeList []LocatedNode
LocatedNodeList is a list of nodes selected by a JSONPath query, along with their NormalizedPath locations.
func QueryJSONLocated ¶
func QueryJSONLocated(src []byte, path Path) (LocatedNodeList, error)
QueryJSONLocated unmarshals src, preserving JSON numbers as encoding/json.Number, and evaluates path against it, returning matched nodes together with their normalized paths.
Example ¶
package main
import (
"fmt"
"log"
"github.com/agentable/jsonpath"
)
func main() {
src := []byte(`{"store":{"book":[{"title":"Moby Dick"},{"title":"1984"}]}}`)
path := jsonpath.MustParse("$.store.book[*].title")
located, err := jsonpath.QueryJSONLocated(src, path)
if err != nil {
log.Fatal(err)
}
for node := range located.All() {
fmt.Printf("%s = %v\n", node.Path, node.Value)
}
}
Output: $['store']['book'][0]['title'] = Moby Dick $['store']['book'][1]['title'] = 1984
func QueryJSONReadLocated ¶ added in v0.1.4
func QueryJSONReadLocated(r io.Reader, path Path) (LocatedNodeList, error)
QueryJSONReadLocated unmarshals JSON from r, preserving numbers as encoding/json.Number, and evaluates path, returning matched nodes together with their normalized paths.
func (LocatedNodeList) All ¶
func (l LocatedNodeList) All() iter.Seq[LocatedNode]
All returns an iterator over all the located nodes in list.
func (LocatedNodeList) Deduplicate ¶
func (l LocatedNodeList) Deduplicate() LocatedNodeList
Deduplicate deduplicates the nodes in list based on their NormalizedPath values, modifying the contents of list. It returns the modified list, which may have a shorter length, and zeroes the elements between the new length and the original length.
func (LocatedNodeList) Paths ¶
func (l LocatedNodeList) Paths() iter.Seq[NormalizedPath]
Paths returns an iterator over all the NormalizedPath values in list.
func (LocatedNodeList) Sort ¶
func (l LocatedNodeList) Sort()
Sort sorts list by the NormalizedPath of each node.
type Logical ¶ added in v0.1.16
type Logical = ast.TypedLogical
Logical is a logical value passed to or returned from a JSONPath function.
type NodeList ¶
type NodeList []any
NodeList is a list of nodes selected by a JSONPath query. Each node represents a single JSON value selected from the JSON query argument.
func QueryJSON ¶
QueryJSON unmarshals src, preserving JSON numbers as encoding/json.Number, and evaluates path against it.
func QueryJSONRead ¶ added in v0.1.4
QueryJSONRead unmarshals JSON from r, preserving numbers as encoding/json.Number, and evaluates path.
type Nodes ¶ added in v0.1.16
type Nodes = ast.TypedNodes
Nodes is a node-list value passed to or returned from a JSONPath function.
type NormalizedPath ¶
type NormalizedPath struct {
// contains filtered or unexported fields
}
NormalizedPath is an immutable sequence of Name/Index selectors per RFC 9535 §2.7. The zero value is the root path.
func NewNormalizedPath ¶ added in v0.1.16
func NewNormalizedPath(elements ...PathElement) (NormalizedPath, error)
NewNormalizedPath returns a normalized path from validated elements.
func (NormalizedPath) Append ¶ added in v0.1.16
func (p NormalizedPath) Append(elem PathElement) (NormalizedPath, error)
Append returns a path with a validated element appended.
func (NormalizedPath) Compare ¶
func (p NormalizedPath) Compare(q NormalizedPath) int
Compare compares p to q and returns -1, 0, or 1. Indexes are always considered less than names.
func (NormalizedPath) Element ¶ added in v0.1.16
func (p NormalizedPath) Element(i int) PathElement
Element returns the i'th path element.
func (NormalizedPath) Elements ¶ added in v0.1.16
func (p NormalizedPath) Elements() []PathElement
Elements returns a copy of p's path elements.
func (NormalizedPath) Equal ¶ added in v0.1.16
func (p NormalizedPath) Equal(q NormalizedPath) bool
Equal reports whether p and q contain the same path elements.
func (NormalizedPath) Len ¶ added in v0.1.16
func (p NormalizedPath) Len() int
Len returns the number of path elements.
func (NormalizedPath) MarshalText ¶
func (p NormalizedPath) MarshalText() ([]byte, error)
MarshalText marshals p into its normalized path string. Implements encoding.TextMarshaler.
func (NormalizedPath) Pointer ¶
func (p NormalizedPath) Pointer() string
Pointer returns an RFC 6901 JSON Pointer string, e.g. /a/0.
func (NormalizedPath) String ¶
func (p NormalizedPath) String() string
String returns the normalized path string, e.g. $['a'][0].
type Option ¶
type Option func(*parserOptions)
Option configures a Parser.
func WithFunctions ¶
WithFunctions registers additional filter functions beyond the RFC 9535 built-ins. Function names must follow RFC function-name grammar: a lowercase ASCII letter followed by lowercase ASCII letters, digits, or underscores. Names must not duplicate another registered function or override a built-in.
Example ¶
package main
import (
"fmt"
"log"
"strings"
"github.com/agentable/jsonpath"
)
func hasPrefix(args []jsonpath.FunctionValue) jsonpath.Logical {
if len(args) != 2 {
return jsonpath.Logical(false)
}
value, ok := args[0].(jsonpath.Value)
if !ok || value.IsNothing() {
return jsonpath.Logical(false)
}
prefix, ok := args[1].(jsonpath.Value)
if !ok || prefix.IsNothing() {
return jsonpath.Logical(false)
}
s, ok := value.Any().(string)
if !ok {
return jsonpath.Logical(false)
}
p, ok := prefix.Any().(string)
return jsonpath.Logical(ok && strings.HasPrefix(s, p))
}
func main() {
fn := jsonpath.NewLogicalFunction(
"has_prefix",
[]jsonpath.FuncType{jsonpath.FuncValue, jsonpath.FuncValue},
hasPrefix,
)
parser, err := jsonpath.NewParser(jsonpath.WithFunctions(fn))
if err != nil {
log.Fatal(err)
}
path, err := parser.Parse(`$[?has_prefix(@.sku, "book-")]`)
if err != nil {
log.Fatal(err)
}
items := []any{
map[string]any{"sku": "book-1"},
map[string]any{"sku": "pen-1"},
}
for item := range path.Select(items).All() {
fmt.Println(item.(map[string]any)["sku"])
}
}
Output: book-1
type ParseError ¶ added in v0.1.16
type ParseError struct {
// Offset is the byte offset in the original expression where parsing failed.
Offset int
// Reason is a short human-readable reason for the failure.
Reason string
// Snippet is a short source excerpt around Offset.
Snippet string
// Cause is the underlying lexer, parser, or function validation error.
Cause error
}
ParseError describes a JSONPath parse failure in a program-readable form.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/agentable/jsonpath"
)
func main() {
_, err := jsonpath.Parse(" $.store")
var parseErr *jsonpath.ParseError
if errors.As(err, &parseErr) {
fmt.Println(errors.Is(err, jsonpath.ErrPathParse))
fmt.Println(parseErr.Offset)
fmt.Println(parseErr.Reason)
}
}
Output: true 0 leading whitespace not allowed
func (*ParseError) Error ¶ added in v0.1.16
func (e *ParseError) Error() string
Error returns a human-readable parse error message.
func (*ParseError) Unwrap ¶ added in v0.1.16
func (e *ParseError) Unwrap() error
Unwrap returns the underlying parse failure cause.
type Parser ¶
type Parser struct {
// contains filtered or unexported fields
}
Parser parses JSONPath expressions into Path values, optionally configured with extension functions.
func NewParser ¶
NewParser creates a new Parser configured by opts. Invalid options return an error satisfying ErrFunction.
type Path ¶
type Path struct {
// contains filtered or unexported fields
}
Path is a compiled RFC 9535 JSONPath query. Safe for concurrent use.
func (Path) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (Path) Select ¶
Select returns all nodes matched by p in input. input must be a decoded JSON value (any / []any / map[string]any / primitive).
Example ¶
package main
import (
"fmt"
"log"
"github.com/agentable/jsonpath"
)
func main() {
path, err := jsonpath.Parse("$.store.book[*].author")
if err != nil {
log.Fatal(err)
}
data := map[string]any{
"store": map[string]any{
"book": []any{
map[string]any{"author": "Nigel Rees"},
map[string]any{"author": "Evelyn Waugh"},
},
},
}
for author := range path.Select(data).All() {
fmt.Println(author)
}
}
Output: Nigel Rees Evelyn Waugh
func (Path) SelectLocated ¶
func (p Path) SelectLocated(input any) LocatedNodeList
SelectLocated returns matched nodes paired with their normalized paths.
func (*Path) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler.
type PathElement ¶
type PathElement interface {
// contains filtered or unexported methods
}
PathElement is either a Name (string key) or an Index (array index) in a normalized path. Implemented by NameElement and IndexElement.
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
ast
Package ast defines the JSONPath abstract syntax tree.
|
Package ast defines the JSONPath abstract syntax tree. |
|
functions
Package functions provides the RFC 9535 §2.4 built-in function implementations for JSONPath filter expressions.
|
Package functions provides the RFC 9535 §2.4 built-in function implementations for JSONPath filter expressions. |
|
lexer
Package lexer provides a hand-written, zero-copy lexer for RFC 9535 JSONPath expressions.
|
Package lexer provides a hand-written, zero-copy lexer for RFC 9535 JSONPath expressions. |
|
parser
Package parser provides a recursive descent parser for RFC 9535 JSONPath expressions.
|
Package parser provides a recursive descent parser for RFC 9535 JSONPath expressions. |