-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathjsonpath.go
72 lines (58 loc) · 1.63 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
package jsonpath
import (
"regexp"
"sync"
)
var parseMutex sync.Mutex
var parser = pegJSONPathParser{}
var unescapeRegex = regexp.MustCompile(`\\(.)`)
// Retrieve returns the retrieved JSON using the given JSONPath.
func Retrieve(jsonPath string, src interface{}, config ...Config) ([]interface{}, error) {
jsonPathFunc, err := Parse(jsonPath, config...)
if err != nil {
return nil, err
}
return jsonPathFunc(src)
}
// Parse returns the parser function using the given JSONPath.
func Parse(jsonPath string, config ...Config) (f func(src interface{}) ([]interface{}, error), err error) {
parseMutex.Lock()
defer func() {
if exception := recover(); exception != nil {
if _err, ok := exception.(error); ok {
err = _err
}
}
parser.jsonPathParser = jsonPathParser{}
parseMutex.Unlock()
}()
parser.Buffer = jsonPath
if parser.parse == nil {
parser.Init()
} else {
parser.Reset()
}
parser.jsonPathParser.unescapeRegex = unescapeRegex
if len(config) > 0 {
parser.jsonPathParser.filterFunctions = config[0].filterFunctions
parser.jsonPathParser.aggregateFunctions = config[0].aggregateFunctions
parser.jsonPathParser.accessorMode = config[0].accessorMode
}
parser.Parse()
parser.Execute()
root := parser.jsonPathParser.root
return func(src interface{}) ([]interface{}, error) {
container := getContainer()
defer func() {
putContainer(container)
}()
if err := root.retrieve(src, src, container); err != nil {
return nil, err.(error)
}
result := make([]interface{}, len(container.result))
for index := range result {
result[index] = container.result[index]
}
return result, nil
}, nil
}