forked from cespare/jsonpath
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjsonpath.go
More file actions
70 lines (60 loc) · 1.15 KB
/
jsonpath.go
File metadata and controls
70 lines (60 loc) · 1.15 KB
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
package main
import (
"bufio"
"encoding/json"
"flag"
"fmt"
"os"
)
func printPaths(v interface{}, key, path string) {
switch v := v.(type) {
case map[string]interface{}:
for mk, mv := range v {
p := path + "." + mk
if mk == key {
fmt.Printf("%v [%v]\n", p, mv)
}
printPaths(mv, key, p)
}
case []interface{}:
for i, sv := range v {
printPaths(sv, key, fmt.Sprintf("%s[%d]", path, i))
}
}
}
func usage() {
fmt.Fprintf(os.Stderr, `usage:
%s key
where key is the key to search for in JSON structures passed to standard input.
`, os.Args[0])
}
func fatalln(args ...interface{}) {
fmt.Fprintln(os.Stderr, args...)
os.Exit(1)
}
func main() {
flag.Usage = usage
flag.Parse()
if flag.NArg() != 1 {
usage()
os.Exit(1)
}
key := flag.Arg(0)
scanner := bufio.NewScanner(os.Stdin)
bytes := make([]byte, 0)
for scanner.Scan() {
b := scanner.Bytes()
if len(b) == 0 {
continue
}
bytes = append(bytes, b...)
}
var v interface{}
if err := json.Unmarshal(bytes, &v); err != nil {
fmt.Fprintf(os.Stderr, "JSON parsing error: %s\n", err)
}
printPaths(v, key, "")
if err := scanner.Err(); err != nil {
fatalln(err)
}
}