-
Notifications
You must be signed in to change notification settings - Fork 38
/
jsonpath.go
76 lines (63 loc) · 2 KB
/
jsonpath.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Package jsonpath is an implementation of http://goessner.net/articles/JsonPath/
// If a JSONPath contains one of
// [key1, key2 ...], .., *, [min:max], [min:max:step], (? expression)
// all matchs are listed in an []interface{}
//
// The package comes with an extension of JSONPath to access the wildcard values of a match.
// If the JSONPath is used inside of a JSON object, you can use placeholder '#' or '#i' with natural number i
// to access all wildcards values or the ith wildcard
//
// This package can be extended with gval modules for script features like multiply, length, regex or many more.
// So take a look at github.com/PaesslerAG/gval.
package jsonpath
import (
"context"
"github.com/PaesslerAG/gval"
)
type Array interface {
gval.Selector
Len() int
ForEach(func(key string, v interface{}))
}
type Object interface {
gval.Selector
ForEach(func(key string, v interface{}))
}
// New returns an selector for given JSONPath
func New(path string) (gval.Evaluable, error) {
return lang.NewEvaluable(path)
}
// Get executes given JSONPath on given value
func Get(path string, value interface{}) (interface{}, error) {
eval, err := lang.NewEvaluable(path)
if err != nil {
return nil, err
}
return eval(context.Background(), value)
}
func GetWithPaths(path string, value interface{}) (interface{}, error) {
ctx := context.WithValue(context.Background(), CollectFullPathsContextKey{}, true)
eval, err := lang.NewEvaluableWithContext(ctx, path)
if err != nil {
return nil, err
}
return eval(ctx, value)
}
var lang = gval.NewLanguage(
gval.Base(),
gval.PrefixExtension('$', parseRootPath),
gval.PrefixExtension('@', parseCurrentPath),
)
// Language is the JSONPath Language
func Language() gval.Language {
return lang
}
var placeholderExtension = gval.NewLanguage(
lang,
gval.PrefixExtension('{', parseJSONObject),
gval.PrefixExtension('#', parsePlaceholder),
)
// PlaceholderExtension is the JSONPath Language with placeholder
func PlaceholderExtension() gval.Language {
return placeholderExtension
}