-
Notifications
You must be signed in to change notification settings - Fork 1
/
jqingo.go
73 lines (54 loc) · 1.32 KB
/
jqingo.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
package jqingo
import (
"bytes"
"encoding/json"
"os"
)
// ProcessCommand takes all arguments from the command line and does work accordingly
func ProcessCommand(compact bool, args []string) (err error) {
selector := args[0]
input := args[1]
selectedJSON, err := getSelectedJSON(selector, input)
output, err := formatOutput(compact, selectedJSON)
if err != nil {
return
}
printOutput(output)
return
}
func printOutput(input []byte) {
os.Stdout.Write(input)
}
func formatOutput(compact bool, input string) (output []byte, err error) {
output = []byte{}
// If compact flag is on
if compact {
output, err = compactOutput(input)
return
}
var f interface{}
// Read as data
if err = json.Unmarshal([]byte(input), &f); err != nil {
return
}
// MarshalIndent can't throw error because
// f is a proper JSON from Unmarshal earlier
output, _ = json.MarshalIndent(f, "", " ")
return
}
func compactOutput(input string) (output []byte, err error) {
var f interface{}
var c []byte
// Read as data
if err = json.Unmarshal([]byte(input), &f); err != nil {
return
}
// Marshal can't throw error because
// f is a proper JSON from Unmarshal earlier
c, _ = json.Marshal(f)
buffer := new(bytes.Buffer)
// c is proper JSON from Marshal above
_ = json.Compact(buffer, c)
output = buffer.Bytes()
return
}