-
Notifications
You must be signed in to change notification settings - Fork 71
/
command_jq.go
72 lines (59 loc) · 1.21 KB
/
command_jq.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 utils
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"github.com/hokaccha/go-prettyjson"
"github.com/itchyny/gojq"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
var cmdJq = &cobra.Command{
Use: "jq",
Short: "Parse json strings",
Long: `Parse json strings
The jq subcommand makes use of gojq (https://github.com/itchyny/gojq) to provide
json parsing capabilities.
`,
Example: `echo '{"foo": 128}' | newrelic utils jq '.foo'`,
Args: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
log.Fatalln("no filter string provided")
}
if !StdinExists() {
log.Fatalln("no input found")
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
query, err := gojq.Parse(args[0])
if err != nil {
log.Fatalln(err)
}
bytes, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Fatalln(err)
}
var obj interface{}
err = json.Unmarshal(bytes, &obj)
if err != nil {
log.Fatalln(err)
}
iter := query.Run(obj)
for {
v, ok := iter.Next()
if !ok {
break
}
if err, ok := v.(error); ok {
log.Fatalln(err)
}
s, _ := prettyjson.Marshal(v)
fmt.Println(string(s))
}
},
}
func init() {
Command.AddCommand(cmdJq)
}