-
Notifications
You must be signed in to change notification settings - Fork 0
/
render.go
43 lines (37 loc) · 1.02 KB
/
render.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
package cliutil
import (
"encoding/json"
"fmt"
jmespath "github.com/jmespath/go-jmespath"
)
// FormatJSON returns pretty-printed JSON as a string.
func FormatJSON(v interface{}) (string, error) {
b, err := json.MarshalIndent(v, "", " ")
return string(b), err
}
// FormatJSONWithFilter applies a JMESPath filter and returns pretty-printed
// JSON as a string and panics on any marshal errors.
func FormatJSONWithFilter(v interface{}, filter string) (out string, err error) {
if filter != "" {
if v, err = jmespath.Search(filter, v); err != nil {
return
}
}
out, err = FormatJSON(v)
return
}
// PrintJSON writes pretty-printed JSON to STDOUT.
func PrintJSON(v interface{}) (err error) {
var out string
if out, err = FormatJSON(v); err == nil {
_, err = fmt.Println(out)
}
return
}
// PrintJSONWithFilter applies a JMESPath filter and writes pretty-printed JSON
// to STDOUT.
func PrintJSONWithFilter(v interface{}, filter string) error {
s, err := FormatJSONWithFilter(v, filter)
fmt.Println(s)
return err
}