jp

package
v1.28.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 16, 2026 License: MIT Imports: 14 Imported by: 114

Documentation

Overview

Package jp provides JSONPath implementation that operations on simple go types, generic (gen package), and public struct with public members. Get, set, and delete operations can be evaluated on data. When needed reflection is used to follow a path.

Index

Examples

Constants

This section is empty.

Variables

View Source
var CompileScript func(code []byte) Procedure

CompileScript if non-nil should return object that implments the Procedure interface. This function is called when a script notation bracketed by [( and )] is encountered. Note the string code argument will included the open and close parenthesis but not the square brackets.

View Source
var (

	// Nothing can be used in scripts to indicate no value as in a script such
	// as [?(@.x == Nothing)] this indicates there was no value as @.x. It is
	// the same as [?(@.x has false)] or [?(@.x exists false)].
	Nothing = nothing(0)
)

Functions

func AppendString added in v1.18.2

func AppendString(buf []byte, s string, delim byte) []byte

AppendString to a buffer while escaping characters as necessary.

func PathMatch added in v1.24.0

func PathMatch(target, path Expr) bool

PathMatch returns true if the provided path would match the target expression. The path argument is expected to be a normalized path with only elements of Root ($), At (@), Child (string), or Nth (int). A Filter fragment in the target expression will match any value in path since it requires data from a JSON document to be evaluated. Slice fragments always return true as long as the path element is an Nth.

func RegisterBinaryFunction added in v1.23.0

func RegisterBinaryFunction(name string, getLeft, getRight bool, f func(left, right any) any)

RegisterBinaryFunction registers a function that takes two argument for scripts. The 'getLeft' and 'getRight' arguments if true indicates a get operation to provide the argument to the provided function otherwise the first match is used. Names must be alpha characters only.

func RegisterUnaryFunction added in v1.23.0

func RegisterUnaryFunction(name string, get bool, f func(arg any) any)

RegisterUnaryFunction registers a unary function for scripts. The 'get' argument if true indicates a get operation to provide the argument to the provided function otherwise the first match is used. Names must be alpha characters only.

func Walk added in v1.13.0

func Walk(data any, cb func(path Expr, value any), justLeaves ...bool)

Walk data and call the cb callback for each node in the data. The path is reused in each call so if the path needs to be save it should be copied.

Types

type At

type At byte

At is the @ in a JSON path representation.

func (At) Append

func (f At) Append(buf []byte, bracket, first bool) []byte

Append a fragment string representation of the fragment to the buffer then returning the expanded buffer.

func (At) Walk added in v1.25.0

func (f At) Walk(rest, path Expr, nodes []any, cb func(path Expr, nodes []any))

Walk continues with the next in rest.

type Bracket

type Bracket byte

Bracket is used as a flag to indicate the path should be displayed in a bracketed representation.

func (Bracket) Append

func (f Bracket) Append(buf []byte, bracket, first bool) []byte

Append a fragment string representation of the fragment to the buffer then returning the expanded buffer.

func (Bracket) Walk added in v1.25.0

func (f Bracket) Walk(rest, path Expr, nodes []any, cb func(path Expr, nodes []any))

Walk continues with the next in rest.

type Child

type Child string

Child is a child operation for a JSON path expression.

func (Child) Append

func (f Child) Append(buf []byte, bracket, first bool) []byte

Append a fragment string representation of the fragment to the buffer then returning the expanded buffer.

func (Child) Walk added in v1.25.0

func (f Child) Walk(rest, path Expr, nodes []any, cb func(path Expr, nodes []any))

Walk follows the matching element in a map or map like element.

type Descent

type Descent byte

Descent is used as a flag to indicate the path should be displayed in a recursive descent representation.

func (Descent) Append

func (f Descent) Append(buf []byte, bracket, first bool) []byte

Append a fragment string representation of the fragment to the buffer then returning the expanded buffer.

func (Descent) Walk added in v1.25.0

func (f Descent) Walk(rest, path Expr, nodes []any, cb func(path Expr, nodes []any))

Walk each element in the tree of elements.

type Equation

type Equation struct {
	// contains filtered or unexported fields
}

Equation represents JSON Path script and filter equations. They are used to build a script. The purpose of the Equation is to allow scripts or filters to be created without using a parser which could return an error if an invalid string representation of the script is provided.

func Add

func Add(left, right *Equation) *Equation

Add creates and returns an Equation for a + operator.

func And

func And(left, right *Equation) *Equation

And creates and returns an Equation for a && operator.

func ConstBool

func ConstBool(b bool) *Equation

ConstBool creates and returns an Equation for a bool constant.

func ConstFloat

func ConstFloat(f float64) *Equation

ConstFloat creates and returns an Equation for a float64 constant.

func ConstInt

func ConstInt(i int64) *Equation

ConstInt creates and returns an Equation for an int64 constant.

func ConstList added in v1.14.0

func ConstList(list []any) *Equation

ConstList creates and returns an Equation for an []any constant.

func ConstNil

func ConstNil() *Equation

ConstNil creates and returns an Equation for a constant of nil.

func ConstNothing added in v1.18.0

func ConstNothing() *Equation

ConstNothing creates and returns an Equation for a constant of nothing.

func ConstRegex added in v1.14.0

func ConstRegex(rx *regexp.Regexp) *Equation

ConstRegex creates and returns an Equation for a regex constant.

func ConstString

func ConstString(s string) *Equation

ConstString creates and returns an Equation for a string constant.

func Count added in v1.18.0

func Count(x Expr) *Equation

Count creates and returns an Equation for a count function.

func Divide

func Divide(left, right *Equation) *Equation

Divide creates and returns an Equation for a / operator.

func Empty added in v1.14.0

func Empty(left, right *Equation) *Equation

Empty creates and returns an Equation for an empty operator.

func Eq

func Eq(left, right *Equation) *Equation

Eq creates and returns an Equation for an == operator.

func Exists added in v1.18.0

func Exists(left, right *Equation) *Equation

Exists creates and returns an Equation for a exists operator.

func Get

func Get(x Expr) *Equation

Get creates and returns an Equation for an expression get of the form @.child.

func Gt

func Gt(left, right *Equation) *Equation

Gt creates and returns an Equation for a > operator.

func Gte

func Gte(left, right *Equation) *Equation

Gte creates and returns an Equation for a >= operator.

func Has added in v1.17.0

func Has(left, right *Equation) *Equation

Has creates and returns an Equation for a has operator.

func In added in v1.14.0

func In(left, right *Equation) *Equation

In creates and returns an Equation for an in operator.

func Length added in v1.18.0

func Length(x Expr) *Equation

Length creates and returns an Equation for a length function.

func Lt

func Lt(left, right *Equation) *Equation

Lt creates and returns an Equation for a < operator.

func Lte

func Lte(left, right *Equation) *Equation

Lte creates and returns an Equation for a <= operator.

func Match added in v1.18.0

func Match(left, right *Equation) *Equation

Match creates and returns an Equation for a match function.

func Multiply

func Multiply(left, right *Equation) *Equation

Multiply creates and returns an Equation for a * operator.

func MustParseEquation added in v1.21.3

func MustParseEquation(str string) (eq *Equation)

MustParseEquation parses the string argument and returns an Equation or panics.

func Neq

func Neq(left, right *Equation) *Equation

Neq creates and returns an Equation for a != operator.

func Not

func Not(arg *Equation) *Equation

Not creates and returns an Equation for a ! operator.

func Or

func Or(left, right *Equation) *Equation

Or creates and returns an Equation for a || operator.

func Regex added in v1.14.0

func Regex(left, right *Equation) *Equation

Regex creates and returns an Equation for a regex operator.

func Search(left, right *Equation) *Equation

Search creates and returns an Equation for a search function.

func Sub

func Sub(left, right *Equation) *Equation

Sub creates and returns an Equation for a - operator.

func (*Equation) Append

func (e *Equation) Append(buf []byte, parens bool) []byte

Append a equation string representation to a buffer.

func (*Equation) Filter

func (e *Equation) Filter() (f *Filter)

Filter creates and returns a Script that implements the equation.

func (*Equation) Script

func (e *Equation) Script() *Script

Script creates and returns a Script that implements the equation.

func (*Equation) String

func (e *Equation) String() string

String representation of the equation.

type Expr

type Expr []Frag

Expr is a JSON path expression composed of fragments. An Expr implements JSONPath as described by https://goessner.net/articles/JsonPath. Where the definition is unclear Oj has implemented the description based on the best judgement of the author.

Example (Noparse)
package main

import (
	"fmt"

	"github.com/ohler55/ojg/jp"
	"github.com/ohler55/ojg/oj"
)

func main() {
	data := map[string]any{
		"a": []any{
			map[string]any{"x": 1, "y": 2, "z": 3},
			map[string]any{"x": 1, "y": 4, "z": 9},
		},
		"b": []any{
			map[string]any{"x": 4, "y": 5, "z": 6},
			map[string]any{"x": 16, "y": 25, "z": 36},
		},
	}
	x := jp.C("b").F(jp.Gt(jp.Get(jp.A().C("y")), jp.ConstInt(10))).C("x")
	fmt.Println(x.String())
	result := x.Get(data)
	fmt.Println(oj.JSON(result, &oj.Options{Sort: true}))
}
Output:

b[?(@.y > 10)].x
[16]

func A

func A() Expr

A creates an Expr with a At (@) fragment.

func B

func B() Expr

B creates an Expr with a Bracket fragment.

func C

func C(key string) Expr

C creates an Expr with a Child fragment.

func D

func D() Expr

D creates an Expr with a recursive Descent fragment.

func F

func F(e *Equation) Expr

F creates an Expr with a Filter fragment.

func MustParse added in v1.11.0

func MustParse(buf []byte) (x Expr)

MustParse parses a []byte into an Expr and panics on error.

func MustParseString added in v1.11.0

func MustParseString(s string) (x Expr)

MustParseString parses a string into an Expr and panics on error.

Example
package main

import (
	"fmt"

	"github.com/ohler55/ojg/jp"
	"github.com/ohler55/ojg/oj"
)

func main() {
	data := map[string]any{
		"a": []any{
			map[string]any{"x": 1, "y": 2, "z": 3},
			map[string]any{"x": 1, "y": 4, "z": 9},
		},
		"b": []any{
			map[string]any{"x": 4, "y": 5, "z": 6},
			map[string]any{"x": 16, "y": 25, "z": 36},
		},
	}
	x := jp.MustParseString("b[?(@.y > 10)].x")
	fmt.Println(x.String())
	result := x.Get(data)
	fmt.Println(oj.JSON(result))
}
Output:

b[?(@.y > 10)].x
[16]

func N

func N(n int) Expr

N creates an Expr with an Nth fragment.

func Parse

func Parse(buf []byte) (x Expr, err error)

Parse parses a []byte into an Expr.

func ParseString

func ParseString(s string) (x Expr, err error)

ParseString parses a string into an Expr.

Example
package main

import (
	"fmt"

	"github.com/ohler55/ojg/jp"
	"github.com/ohler55/ojg/oj"
)

func main() {
	data := map[string]any{
		"a": []any{
			map[string]any{"x": 1, "y": 2, "z": 3},
			map[string]any{"x": 1, "y": 4, "z": 9},
		},
		"b": []any{
			map[string]any{"x": 4, "y": 5, "z": 6},
			map[string]any{"x": 16, "y": 25, "z": 36},
		},
	}
	x, err := jp.ParseString("b[?(@.y > 10)].x")
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	fmt.Println(x.String())
	result := x.Get(data)
	fmt.Println(oj.JSON(result))
}
Output:

b[?(@.y > 10)].x
[16]

func R

func R() Expr

R creates an Expr with a Root fragment.

func S

func S(start int, rest ...int) Expr

S creates an Expr with a Slice fragment.

func U

func U(keys ...any) Expr

U creates an Expr with an Union fragment.

func W

func W() Expr

W creates an Expr with a Wildcard fragment.

func X

func X() Expr

X creates an empty Expr.

func (Expr) A

func (x Expr) A() Expr

A appends an At fragment to the Expr.

func (Expr) Append

func (x Expr) Append(buf []byte, brackets ...bool) []byte

Append a string representation of the expression to a byte slice and return the expanded buffer.

func (Expr) At

func (x Expr) At() Expr

At appends an At fragment to the Expr.

func (Expr) B

func (x Expr) B() Expr

B appends a Bracket fragment to the Expr.

func (Expr) BracketString added in v1.21.0

func (x Expr) BracketString() string

BracketString returns a string representation of the expression using the bracket notation.

func (Expr) C

func (x Expr) C(key string) Expr

C appends a Child fragment to the Expr.

func (Expr) Child

func (x Expr) Child(key string) Expr

Child appends a Child fragment to the Expr.

func (Expr) D

func (x Expr) D() Expr

D appends a recursive Descent fragment to the Expr.

func (Expr) Del

func (x Expr) Del(data any) error

Del removes matching nodes.

Example
package main

import (
	"fmt"

	"github.com/ohler55/ojg"
	"github.com/ohler55/ojg/jp"
	"github.com/ohler55/ojg/sen"
)

func main() {
	data := []any{
		map[string]any{"a": 1, "b": 2, "c": 3},
	}
	if err := jp.N(0).C("b").Del(data); err != nil {
		panic(err)
	}
	fmt.Println(sen.String(data, &ojg.Options{Sort: true}))

}
Output:

[{a:1 c:3}]

func (Expr) DelOne

func (x Expr) DelOne(data any) error

DelOne removes at most one node.

func (Expr) Descent

func (x Expr) Descent() Expr

Descent appends a recursive Descent fragment to the Expr.

func (Expr) F

func (x Expr) F(e *Equation) Expr

F appends a Filter fragment to the Expr.

func (Expr) Filter

func (x Expr) Filter(e *Equation) Expr

Filter appends a Filter fragment to the Expr.

func (Expr) First

func (x Expr) First(data any) any

First element of the data identified by the path.

func (Expr) FirstFound added in v1.18.0

func (x Expr) FirstFound(data any) (any, bool)

FirstFound element of the data identified by the path.

func (Expr) FirstNode

func (x Expr) FirstNode(n gen.Node) (result gen.Node)

FirstNode returns the first matcning node.

func (Expr) Get

func (x Expr) Get(data any) (results []any)

Get the elements of the data identified by the path.

func (Expr) GetNodes

func (x Expr) GetNodes(n gen.Node) (results []gen.Node)

GetNodes the elements of the data identified by the path.

func (Expr) Has added in v1.13.0

func (x Expr) Has(data any) bool

Has returns true if there is a value ot the end of the path specified. A nil value is still a value.

func (Expr) Locate added in v1.21.0

func (x Expr) Locate(data any, max int) (locs []Expr)

Locate the values described by the Expr and return a slice of normalized paths to those values in the data. The returned slice is limited to the max specified. A max of 0 or less indicates there is no maximum.

func (Expr) Modify added in v1.17.0

func (x Expr) Modify(data any, modifier func(element any) (altered any, changed bool)) (result any, err error)

Modify modifies matching nodes and panics on an expression error. Modified elements replace the original element in the data. The modified data is returned. Unless the data is a slice and modified the returned data will be the same object as the original. The modifier function will be called with the elements that match the path and should return the original element or if altered the altered value along with setting the returned changed value to true.

func (Expr) ModifyOne added in v1.17.0

func (x Expr) ModifyOne(data any, modifier func(element any) (altered any, changed bool)) (result any, err error)

ModifyOne modifies matching nodes and panics on an expression error. Modified elements replace the original element in the data. The modified data is returned. Unless the data is a slice and modified the returned data will be the same object as the original. The modifier function will be called with the elements that match the path and should return the original element or if altered the altered value along with setting the returned changed value to true. The function returns after the first modification.

func (Expr) MustDel added in v1.11.0

func (x Expr) MustDel(data any)

MustDel removes matching nodes and panics on error.

Example
package main

import (
	"fmt"

	"github.com/ohler55/ojg"
	"github.com/ohler55/ojg/jp"
	"github.com/ohler55/ojg/sen"
)

func main() {
	data := []any{
		map[string]any{"a": 1, "b": 2, "c": 3},
	}
	jp.N(0).C("b").MustDel(data)
	fmt.Println(sen.String(data, &ojg.Options{Sort: true}))
}
Output:

[{a:1 c:3}]

func (Expr) MustDelOne added in v1.16.0

func (x Expr) MustDelOne(data any)

MustDelOne removes one matching node and panics on error.

func (Expr) MustModify added in v1.17.0

func (x Expr) MustModify(data any, modifier func(element any) (altered any, changed bool)) any

MustModify modifies matching nodes and panics on an expression error. In go, maps can be modified in place as the map itself is modified. Slice elements can be replaced in place but elements can not be added or removed without potentially needing to replace the original slice with a new one. This function and the other jp.Modify functions allow a slice to be replaced by stopping at the parent of the target slice and applying a modifier function to the target which is then replaced in the parent. Without that functionality slice element can only be replaced.

Modified elements replace the original element in the data. The modified data is returned. Unless the data is a slice and modified the returned data will be the same object as the original. The modifier function will be called with the elements that match the path and should return the original element or if altered the altered value along with setting the returned changed value to true.

func (Expr) MustModifyOne added in v1.17.0

func (x Expr) MustModifyOne(data any, modifier func(element any) (altered any, changed bool)) any

MustModifyOne modifies matching nodes and panics on an expression error. Modified elements replace the original element in the data. The modified data is returned. Unless the data is a slice and modified the returned data will be the same object as the original. The modifier function will be called with the elements that match the path and should return the original element or if altered the altered value along with setting the returned changed value to true. The function returns after the first modification.

func (Expr) MustRemove added in v1.16.0

func (x Expr) MustRemove(data any) any

MustRemove removes matching nodes and panics on an expression error but silently makes no changes if there is no match for the expression. Removed slice elements are removed and the remaining elements are moveed to fill in the removed element. The slice is shortened.

func (Expr) MustRemoveOne added in v1.16.0

func (x Expr) MustRemoveOne(data any) any

MustRemoveOne removes matching nodes and panics on an expression error but silently makes no changes if there is no match for the expression. Removed slice elements are removed and the remaining elements are moveed to fill in the removed element. The slice is shortened.

func (Expr) MustSet added in v1.11.0

func (x Expr) MustSet(data, value any)

MustSet all matching child node values. If the path to the child does not exist array and map elements are added. Panics on error.

Example
package main

import (
	"fmt"

	"github.com/ohler55/ojg"
	"github.com/ohler55/ojg/jp"
	"github.com/ohler55/ojg/sen"
)

func main() {
	data := []any{
		map[string]any{"a": 1, "b": 2, "c": 3},
	}
	// Set members with a JSONPath expression.
	jp.N(0).C("b").MustSet(data, 7)
	fmt.Println(sen.String(data, &ojg.Options{Sort: true}))

	// Add members with a JSONPath expression.
	jp.N(0).C("d").MustSet(data, 4)
	fmt.Println(sen.String(data, &ojg.Options{Sort: true}))

}
Output:

[{a:1 b:7 c:3}]
[{a:1 b:7 c:3 d:4}]

func (Expr) MustSetOne added in v1.16.0

func (x Expr) MustSetOne(data, value any)

MustSetOne child node value. If the path to the child does not exist array and map elements are added. Panics on error.

func (Expr) N

func (x Expr) N(n int) Expr

N appends an Nth fragment to the Expr.

func (Expr) Normal added in v1.21.2

func (x Expr) Normal() bool

Normal returns true if the only fragments in the expression are root, at, child, and nth.

func (Expr) Nth

func (x Expr) Nth(n int) Expr

Nth appends an Nth fragment to the Expr.

func (Expr) R

func (x Expr) R() Expr

R appends a Root fragment to the Expr.

func (Expr) Remove added in v1.16.0

func (x Expr) Remove(data any) (result any, err error)

Remove removes matching nodes. An error is returned for an expression error but silently makes no changes if there is no match for the expression. Removed slice elements are removed and the remaining elements are moveed to fill in the removed element. The slice is shortened.

func (Expr) RemoveOne added in v1.16.0

func (x Expr) RemoveOne(data any) (result any, err error)

RemoveOne removes at most one node. An error is returned for an expression error but silently makes no changes if there is no match for the expression. Removed slice elements are removed and the remaining elements are moveed to fill in the removed element. The slice is shortened.

func (Expr) Root

func (x Expr) Root() Expr

Root appends a Root fragment to the Expr.

func (Expr) S

func (x Expr) S(start int, rest ...int) Expr

S appends a Slice fragment to the Expr.

func (Expr) Set

func (x Expr) Set(data, value any) error

Set all matching child node values. An error is returned if it is not possible. If the path to the child does not exist array and map elements are added.

Example
package main

import (
	"fmt"

	"github.com/ohler55/ojg"
	"github.com/ohler55/ojg/jp"
	"github.com/ohler55/ojg/sen"
)

func main() {
	data := []any{
		map[string]any{"a": 1, "b": 2, "c": 3},
	}
	// Set members with a JSONPath expression.
	if err := jp.N(0).C("b").Set(data, 7); err != nil {
		panic(err)
	}
	fmt.Println(sen.String(data, &ojg.Options{Sort: true}))

	// Add members with a JSONPath expression.
	if err := jp.N(0).C("d").Set(data, 4); err != nil {
		panic(err)
	}
	fmt.Println(sen.String(data, &ojg.Options{Sort: true}))

}
Output:

[{a:1 b:7 c:3}]
[{a:1 b:7 c:3 d:4}]

func (Expr) SetOne

func (x Expr) SetOne(data, value any) error

SetOne child node value. An error is returned if it is not possible. If the path to the child does not exist array and map elements are added.

func (Expr) Slice

func (x Expr) Slice(start int, rest ...int) Expr

Slice appends a Slice fragment to the Expr.

func (Expr) String

func (x Expr) String() string

String returns a string representation of the expression.

func (Expr) U

func (x Expr) U(keys ...any) Expr

U appends a Union fragment to the Expr.

func (Expr) Union

func (x Expr) Union(keys ...any) Expr

Union appends a Union fragment to the Expr.

func (Expr) W

func (x Expr) W() Expr

W appends a Wildcard fragment to the Expr.

func (Expr) Walk added in v1.25.0

func (x Expr) Walk(data any, cb func(path Expr, nodes []any))

Walk the matching elements in the data and call cb on the matches. The path passed to the cb function is the normalized path to the current location while the nodes are the chain of elements up to and including the current element.

func (Expr) Wildcard

func (x Expr) Wildcard() Expr

Wildcard appends a Wildcard fragment to the Expr.

type Filter

type Filter struct {
	Script
}

Filter is a script used as a filter.

func MustNewFilter added in v1.11.0

func MustNewFilter(str string) (f *Filter)

MustNewFilter creates a new Filter and panics on error.

func NewFilter

func NewFilter(str string) (f *Filter, err error)

NewFilter creates a new Filter.

func (*Filter) Append

func (f *Filter) Append(buf []byte, _, _ bool) []byte

Append a fragment string representation of the fragment to the buffer then returning the expanded buffer.

func (*Filter) String

func (f *Filter) String() string

String representation of the filter.

func (*Filter) Walk added in v1.25.0

func (f *Filter) Walk(rest, path Expr, nodes []any, cb func(path Expr, nodes []any))

Walk each element that matches the filter.

type Form added in v1.15.0

type Form struct {
	// Op is the operation to perform.
	Op string

	// Left is the left side a form. The type can be a *Form, Expr, or any of
	// the simple types.
	Left any

	// Right is the left side a form. The type can be a *Form, Expr, or any of
	// the simple types.
	Right any
}

Form represents a component of a JSON Path script and filter. They are used inspect a Script or Filter. The general template for a Form is (left op right). For an operations such as not (!) the right side is left as nil. As an example a Filter fragment of [?(@.x == 3)] whould be representing in a Form as

Form{Op: "==", Left: jp.Expr{jp.At('@'), jp.Child("x")}, Right: 3}.

func (*Form) Simplify added in v1.15.0

func (f *Form) Simplify() any

Simplify the form.

type Frag

type Frag interface {

	// Append a fragment string representation of the fragment to the buffer
	// then returning the expanded buffer.
	Append(buf []byte, bracket, first bool) []byte

	// Walk the matching elements in tail of nodes and call cb on the matches
	// or follow on to the matching if not the last fragment in an
	// expression. The rest argument is the rest of the expression after this
	// fragment. The path is the normalized path up to this point. The nodes
	// argument is the chain of data elements to the current location.
	Walk(rest, path Expr, nodes []any, cb func(path Expr, nodes []any))
	// contains filtered or unexported methods
}

Frag represents a JSONPath fragment. A JSONPath expression is composed of fragments (Frag) linked together to form a full path expression.

type Indexed added in v1.18.2

type Indexed interface {

	// ValueAtIndex should return the value at the provided index or nil if no
	// entry exists at the index.
	ValueAtIndex(index int) any

	// SetValueAtIndex should set the value at the provided index.
	SetValueAtIndex(index int, value any)

	// Size should return the size for the collection.
	Size() int
}

Indexed describes an interface for a collection that is indexed by a integers similar to a []any.

type Keyed added in v1.18.2

type Keyed interface {

	// ValueForKey should return the value associated with the key or nil if
	// no entry exists for the key.
	ValueForKey(key string) (value any, has bool)

	// SetValueForKey sets the value for a key in the collection.
	SetValueForKey(key string, value any)

	// RemoveValueForKey removes the value for a key in the collection.
	RemoveValueForKey(key string)

	// Keys should return an list of the keys for all the entries in the
	// collection.
	Keys() []string
}

Keyed describes an interface for a collection that is indexed by a string key similar to a map[string]any.

type MatchHandler added in v1.24.0

type MatchHandler struct {
	Targets []*TargetRest
	Path    Expr
	Stack   []any
	OnData  func(path Expr, data any)
}

PathHandler is a TokenHandler compatible with both the oj.TokenHandler and the sen.TokenHandler. Fields are public to allow derived types to access those fields.

func NewMatchHandler added in v1.24.0

func NewMatchHandler(onData func(path Expr, data any), targets ...Expr) *MatchHandler

NewMatchHandler creates a new MatchHandler.

func (*MatchHandler) AddValue added in v1.24.0

func (h *MatchHandler) AddValue(v any)

AddValue is called when a leaf value is encountered.

func (*MatchHandler) ArrayEnd added in v1.24.0

func (h *MatchHandler) ArrayEnd()

ArrayEnd is called when a JSON array end ']' is encountered.

func (*MatchHandler) ArrayStart added in v1.24.0

func (h *MatchHandler) ArrayStart()

ArrayStart is called when a JSON array start '[' is encountered.

func (*MatchHandler) Bool added in v1.24.0

func (h *MatchHandler) Bool(v bool)

Bool is called when a JSON true or false is encountered.

func (*MatchHandler) Float added in v1.24.0

func (h *MatchHandler) Float(v float64)

Float is called when a JSON decimal is encountered that fits into a float64.

func (*MatchHandler) Int added in v1.24.0

func (h *MatchHandler) Int(v int64)

Int is called when a JSON integer is encountered.

func (*MatchHandler) Key added in v1.24.0

func (h *MatchHandler) Key(k string)

Key is called when a JSON object key is encountered.

func (*MatchHandler) Null added in v1.24.0

func (h *MatchHandler) Null()

Null is called when a JSON null is encountered.

func (*MatchHandler) Number added in v1.24.0

func (h *MatchHandler) Number(num string)

Number is called when a JSON number is encountered that does not fit into an int64 or float64.

func (*MatchHandler) ObjectEnd added in v1.24.0

func (h *MatchHandler) ObjectEnd()

ObjectEnd is called when a JSON object end '}' is encountered.

func (*MatchHandler) ObjectStart added in v1.24.0

func (h *MatchHandler) ObjectStart()

ObjectStart is called when a JSON object start '{' is encountered.

func (*MatchHandler) String added in v1.24.0

func (h *MatchHandler) String(v string)

String is called when a JSON string is encountered.

type Nth

type Nth int

Nth is a subscript operator that matches the n-th element in an array for a JSON path expression.

func (Nth) Append

func (f Nth) Append(buf []byte, bracket, first bool) []byte

Append a fragment string representation of the fragment to the buffer then returning the expanded buffer.

func (Nth) Walk added in v1.25.0

func (f Nth) Walk(rest, path Expr, nodes []any, cb func(path Expr, nodes []any))

Walk follows the matching element in a slice or slice like element.

type Proc added in v1.26.0

type Proc struct {
	Procedure Procedure
	Script    []byte
}

Proc is a script used as a procedure which is a script not limited to being a selector. While both Locate() and Walk() are supported the results may not be as expected since the procedure can modify the original data. Remove() is not supported with this fragment type.

func MustNewProc added in v1.26.0

func MustNewProc(code []byte) (p *Proc)

MustNewProc creates a new Proc and panics on error.

func (*Proc) Append added in v1.26.0

func (p *Proc) Append(buf []byte, _, _ bool) []byte

Append a fragment string representation of the fragment to the buffer then returning the expanded buffer.

func (*Proc) String added in v1.26.0

func (p *Proc) String() string

String representation of the proc.

func (*Proc) Walk added in v1.26.0

func (p *Proc) Walk(rest, path Expr, nodes []any, cb func(path Expr, nodes []any))

Walk each element returned from the procedure call. Note that this may or may not correspond to the original data as the procedure can modify not only the elements in the original data but also the contents of each.

type Procedure added in v1.26.0

type Procedure interface {
	// Get should return a list of matching in the data element.
	Get(data any) []any

	// First should return a single matching in the data element or nil if
	// there are no matches.
	First(data any) any
}

Procedure defines the interface for functions for script fragments between [( and )] delimiters.

type RemovableIndexed added in v1.24.1

type RemovableIndexed interface {
	Indexed

	// RemoveValueAtIndex removes an item from the collection.
	RemoveValueAtIndex(index int)
}

RemovableIndexed describes an indexed collection that can remove items. Must be implemented to use Expr.Remove.

type Root

type Root byte

Root represents a root $ in a JSON path representation.

func (Root) Append

func (f Root) Append(buf []byte, bracket, first bool) []byte

Append a fragment string representation of the fragment to the buffer then returning the expanded buffer.

func (Root) Walk added in v1.25.0

func (f Root) Walk(rest, path Expr, nodes []any, cb func(path Expr, nodes []any))

Walk continues with the next in rest.

type Script

type Script struct {
	// contains filtered or unexported fields
}

Script represents JSON Path script used in filters as well.

Example
package main

import (
	"fmt"

	"github.com/ohler55/ojg/jp"
	"github.com/ohler55/ojg/oj"
)

func main() {
	data := []any{
		map[string]any{"a": 1, "b": 2, "c": 3},
		map[string]any{"a": int64(52), "b": 4, "c": 6},
	}
	// Build an Equation and generate a Script from the Equation.
	s := jp.Or(
		jp.Lt(jp.Get(jp.A().C("a")), jp.ConstInt(52)),
		jp.Eq(jp.Get(jp.A().C("x")), jp.ConstString("cool")),
	).Script()
	fmt.Println(s.String())
	// Normally Scripts are using in Expr (JSON paths).
	result := s.Eval([]any{}, data)
	fmt.Println(oj.JSON(result, &oj.Options{Sort: true}))
}
Output:

(@.a < 52 || @.x == 'cool')
[{"a":1,"b":2,"c":3}]

func MustNewScript added in v1.11.0

func MustNewScript(str string) (s *Script)

MustNewScript parses the string argument and returns a script or an error.

func NewScript

func NewScript(str string) (s *Script, err error)

NewScript parses the string argument and returns a script or an error.

func (*Script) Append

func (s *Script) Append(buf []byte) []byte

Append a string representation of the fragment to the buffer and then return the expanded buffer.

func (*Script) Eval

func (s *Script) Eval(stack, data any) any

Eval is primarily used by the Expr parser but is public for testing.

func (*Script) Inspect added in v1.15.0

func (s *Script) Inspect() *Form

Inspect the script.

func (*Script) Match

func (s *Script) Match(data any) bool

Match returns true if the script returns true when evaluated against the data argument.

func (*Script) String

func (s *Script) String() string

String representation of the script.

type Slice

type Slice []int

Slice is a slice operation for a JSON path expression.

func (Slice) Append

func (f Slice) Append(buf []byte, _, _ bool) []byte

Append a fragment string representation of the fragment to the buffer then returning the expanded buffer.

func (Slice) Walk added in v1.25.0

func (f Slice) Walk(rest, path Expr, nodes []any, cb func(path Expr, nodes []any))

Walk each element in a slice as defined by the Slice fragment.

type TargetRest added in v1.24.0

type TargetRest struct {
	Target Expr
	// Rest is set when a Filter is included in the initializing target. Since
	// Filters can only be evaluated when there is data for the evaluation a
	// traget with a Filter is split with the pre-filter portion and the rest
	// starting with the filter.
	Rest Expr
}

TargetRest is used by the MatchHandler to associate a Target and Rest of a match search.

type Union

type Union []any

Union is a union operation for a JSON path expression which is a union of a Child and Nth fragment.

func NewUnion

func NewUnion(keys ...any) (u Union)

NewUnion creates a new Union with the provide keys.

func (Union) Append

func (f Union) Append(buf []byte, _, _ bool) []byte

Append a fragment string representation of the fragment to the buffer then returning the expanded buffer.

func (Union) Walk added in v1.25.0

func (f Union) Walk(rest, path Expr, nodes []any, cb func(path Expr, nodes []any))

Walk each element in a union.

type Wildcard

type Wildcard byte

Wildcard is used as a flag to indicate the path should be displayed in a wildcarded representation.

func (Wildcard) Append

func (f Wildcard) Append(buf []byte, bracket, first bool) []byte

Append a fragment string representation of the fragment to the buffer then returning the expanded buffer.

func (Wildcard) Walk added in v1.25.0

func (f Wildcard) Walk(rest, path Expr, nodes []any, cb func(path Expr, nodes []any))

Walk follows the all elements in a map or slice like element.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL