forked from kluctl/kluctl
/
jsonpath.go
127 lines (111 loc) · 2.36 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package uo
import (
"fmt"
"github.com/ohler55/ojg/jp"
log "github.com/sirupsen/logrus"
"regexp"
"strings"
)
var isSimpleIdentifier = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]+$`)
func KeyListToJsonPath(keys []interface{}) string {
p := ""
for _, k := range keys {
if i, ok := k.(int); ok {
p = fmt.Sprintf("%s[%d]", p, i)
} else if s, ok := k.(string); ok {
if isSimpleIdentifier.MatchString(s) {
if p != "" {
p += "."
}
p += s
} else {
if p == "" {
p = "$"
}
if strings.Index(s, "\"") != -1 {
p = fmt.Sprintf("%s['%s']", p, s)
} else {
p = fmt.Sprintf("%s[\"%s\"]", p, s)
}
}
} else {
if p == "" {
p = "$"
}
p = fmt.Sprintf("%s[%v]", p, k)
}
}
return p
}
type MyJsonPath struct {
exp jp.Expr
}
func NewMyJsonPath(p string) (*MyJsonPath, error) {
exp, err := jp.ParseString(p)
if err != nil {
return nil, err
}
return &MyJsonPath{
exp: exp,
}, nil
}
func NewMyJsonPathMust(p string) *MyJsonPath {
j, err := NewMyJsonPath(p)
if err != nil {
log.Fatal(err)
}
return j
}
func (j *MyJsonPath) ListMatchingFields(o *UnstructuredObject) ([][]interface{}, error) {
var ret [][]interface{}
o = o.Clone()
magic := struct{}{}
err := j.exp.Set(o.Object, magic)
if err != nil {
return nil, err
}
_ = o.NewIterator().IterateLeafs(func(it *ObjectIterator) error {
if it.Value() == magic {
var c []interface{}
c = append(c, it.KeyPath()...)
ret = append(ret, c)
}
return nil
})
return ret, nil
}
func (j *MyJsonPath) Get(o interface{}) []interface{} {
return j.exp.Get(o)
}
func (j *MyJsonPath) GetFirst(o interface{}) (interface{}, bool) {
l := j.Get(o)
if len(l) == 0 {
return nil, false
}
return l[0], true
}
func (j *MyJsonPath) GetFirstMap(o interface{}) (map[string]interface{}, bool, error) {
o, found := j.GetFirst(o)
if !found {
return nil, false, nil
}
m, ok := o.(map[string]interface{})
if !ok {
return nil, false, fmt.Errorf("child is not a map")
}
return m, true, nil
}
func (j *MyJsonPath) GetFirstListOfMaps(o interface{}) ([]map[string]interface{}, bool, error) {
o, found := j.GetFirst(o)
if !found {
return nil, false, nil
}
m, ok := o.([]map[string]interface{})
if !ok {
return nil, false, fmt.Errorf("child is not a list of maps")
}
return m, true, nil
}
func (j *MyJsonPath) Del(o interface{}) error {
return j.exp.Del(o)
}