-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonpath.go
54 lines (44 loc) · 1.02 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
package jsonpath
/*
We wrap "github.com/PaesslerAG/jsonpath" so that we can implement some json interface methods on top of the base type.
*/
import (
"context"
"encoding/json"
"github.com/PaesslerAG/gval"
"github.com/PaesslerAG/jsonpath"
)
func GetPathValue(data interface{}, jsonPath JsonPath) (interface{}, error) {
return jsonPath.Path(context.Background(), data)
}
// MustParsePath passes the jsonpath expression or panics on error
func MustParsePath(path string) JsonPath {
compiled, err := jsonpath.New(path)
if err != nil {
panic(err)
}
return JsonPath{compiled, path}
}
type JsonPath struct {
Path gval.Evaluable
str string
}
func (jp *JsonPath) UnmarshalJSON(path []byte) error {
// primary
err := json.Unmarshal(path, &jp.str)
if err != nil {
return err
}
compiled, err := jsonpath.New(jp.str)
if err != nil {
return err
}
jp.Path = compiled
return nil
}
func (jp JsonPath) MarshalJSON() ([]byte, error) {
return json.Marshal(jp.String())
}
func (jp *JsonPath) String() string {
return jp.str
}