This repository has been archived by the owner on Mar 3, 2022. It is now read-only.
/
main.go
120 lines (101 loc) 路 2.09 KB
/
main.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"github.com/hokaccha/go-prettyjson"
"github.com/mattn/go-colorable"
"github.com/robertkrimen/otto"
)
var vm = otto.New()
func main() {
fi, err := os.Stdin.Stat()
if err != nil {
fatal(err)
}
if fi.Mode()&os.ModeNamedPipe == 0 {
usage()
os.Exit(1)
}
buf, err := ioutil.ReadAll(os.Stdin)
if err != nil {
fatal(err)
}
var input interface{}
if err := json.Unmarshal(buf, &input); err != nil {
fatal(err)
}
if err := vm.Set("json", input); err != nil {
fatal(err)
}
value, err := vm.Get("json")
if err != nil {
fatal(err)
}
for _, code := range os.Args[1:] {
value, err = reduce(value, code)
if err != nil {
fatal(err)
}
}
if value.IsUndefined() {
fmt.Fprintln(os.Stderr, "undefined")
return
}
if value.IsString() {
fmt.Println(value)
return
}
i, err := value.Export()
if err != nil {
fatal(err)
}
s, err := prettyjson.Marshal(i)
if err != nil {
fatal(err)
}
fmt.Fprintln(colorable.NewColorableStdout(), string(s))
}
func reduce(value otto.Value, code string) (otto.Value, error) {
if err := vm.Set("json", value); err != nil {
fatal(err)
}
switch {
case code == "?":
code = "Object.keys(json)"
case code == ".":
code = "(function () {return this;}).call(json)"
case len(code) > 1 && code[0] == '.':
code = fmt.Sprintf(`(function () {return this%v;}).call(json)`, code)
default:
code = fmt.Sprintf(`(function () {return %v;}).call(json)`, code)
}
result, err := vm.Run(code)
if err != nil {
return otto.UndefinedValue(), err
}
return result, nil
}
func usage() {
fmt.Fprintf(os.Stderr, `
Command-line JSON processing tool
Usage
$ xx [code ...]
Examples
$ echo '{"key": "value"}' | xx 'this.key'
"value"
$ echo '[1,2,3]' | xx 'this.map(function (x) { return x * 2; })'
[2, 4, 6]
$ echo '{"items": ["one", "two"]}' | xx 'this.items' 'this[1]'
"two"
$ echo '{"foo": 1, "bar": 2}' | xx ?
["foo", "bar"]
$ echo '{"key": "value"}' | xx .key
value
`)
}
func fatal(err error) {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}