-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
91 lines (74 loc) · 1.42 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
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"log"
"os"
"regexp"
"strconv"
"strings"
)
func findValueAtPath(a map[string]any, path []string) (any, error) {
var v any = a
for _, part := range path {
if arr, ok := v.([]any); ok {
array_index, err := strconv.Atoi(part)
if err != nil {
return nil, errors.New("invalid path")
}
if array_index > len(arr)-1 {
return nil, errors.New("path not found")
}
v = arr[array_index]
continue
}
m, ok := v.(map[string]any)
if !ok {
return nil, nil
}
v, ok = m[part]
if !ok {
return nil, errors.New("path not found")
}
}
return v, nil
}
func parseJsonAndFind(in io.Reader, path []string) {
dec := json.NewDecoder(in)
var input map[string]any
for {
err := dec.Decode(&input)
if err == io.EOF {
break
}
if err != nil {
fmt.Println("invalid json")
return
}
output, err := findValueAtPath(input, path)
if err != nil {
fmt.Println(err)
return
}
bytes, err := json.MarshalIndent(output, "", " ")
fmt.Println(string(bytes))
if err != nil {
log.Fatal(err)
}
}
}
func argsToPath(args []string) []string {
if len(args) == 1 {
return make([]string, 0)
}
ereg := regexp.MustCompile(`\[([0-9]+)\]`)
arg := ereg.ReplaceAllString(args[1], ".$1")
arg = strings.TrimLeft(arg, ".")
return strings.Split(arg, ".")
}
func main() {
path := argsToPath(os.Args)
parseJsonAndFind(os.Stdin, path)
}