This repository was archived by the owner on May 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
60 lines (48 loc) · 1.3 KB
/
main.go
File metadata and controls
60 lines (48 loc) · 1.3 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
package main
import (
"encoding/json"
"os"
jsonpointer "github.com/galdor/go-json-pointer"
"github.com/galdor/go-program"
)
func main() {
var c *program.Command
p := program.NewProgram("json-pointer",
"utilities for the go-json-pointer library")
c = p.AddCommand("find",
"extract and print the json value referenced by a pointer", cmdFind)
c.AddArgument("pointer", "the json pointer")
c.AddOptionalArgument("path", "the file containing the json document")
p.ParseCommandLine()
p.Run()
}
func cmdFind(p *program.Program) {
pointerString := p.ArgumentValue("pointer")
var pointer jsonpointer.Pointer
if err := pointer.Parse(pointerString); err != nil {
p.Fatal("invalid json pointer: %v", err)
}
filePath := p.ArgumentValue("path")
var file *os.File
if filePath == "" {
file = os.Stdin
} else {
var err error
file, err = os.Open(filePath)
if err != nil {
p.Fatal("cannot open %q: %v", filePath, err)
}
}
defer file.Close()
decoder := json.NewDecoder(file)
var document interface{}
if err := decoder.Decode(&document); err != nil {
p.Fatal("cannot parse json data: %v", err)
}
value := pointer.Find(document)
encoder := json.NewEncoder(os.Stdout)
encoder.SetIndent("", " ")
if err := encoder.Encode(value); err != nil {
p.Fatal("cannot serialize json value: %v", err)
}
}