-
Notifications
You must be signed in to change notification settings - Fork 1
/
io_jsonpath.go
51 lines (43 loc) · 1.18 KB
/
io_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
package cli
import (
"bytes"
"strings"
json "github.com/json-iterator/go"
"k8s.io/client-go/util/jsonpath"
)
const DefaultJSONPathTemplate = "{}"
// JSONPathOutput renders a JSONPath template given in Kubernetes CLI format.
// More information: https://kubernetes.io/docs/reference/kubectl/jsonpath/
// TODO: https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/kubectl/pkg/cmd/get/customcolumn.go
func JSONPathOutput(v interface{}) ([]byte, error) {
// since Go templates are the default, need to reset default template when opting for JSONPath
t := argTemplate
if t == DefaultGoTemplate {
t = DefaultJSONPathTemplate
}
if *flagSimple {
if !strings.Contains(t, "{") {
t = "{" + t + "}"
}
}
j := jsonpath.New("base")
j.EnableJSONOutput(true)
buf := new(bytes.Buffer)
if err := j.Parse(t); err != nil {
return nil, err
}
if err := j.Execute(buf, v); err != nil {
return nil, err
}
// return buf.Bytes(), nil
// TODO: there should be a better way to do this
b := buf.Bytes()
hack := new([]interface{})
if err := json.Unmarshal(b, hack); err != nil {
return nil, err
}
if len(*hack) < 1 {
return nil, nil
}
return json.Marshal((*hack)[0])
}