-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
110 lines (97 loc) · 2.16 KB
/
main.go
File metadata and controls
110 lines (97 loc) · 2.16 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
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
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"os"
"sort"
)
var (
compact = flag.Bool("compact", false, "compact output (no whitespace)")
validate = flag.Bool("validate", false, "validate only, no output")
write = flag.Bool("write", false, "write result back to file")
indent = flag.Int("indent", 2, "number of spaces for indentation")
sortKeys = flag.Bool("sort", false, "sort object keys alphabetically")
)
func main() {
flag.Parse()
var input []byte
var err error
var filename string
if flag.NArg() > 0 {
filename = flag.Arg(0)
input, err = os.ReadFile(filename)
if err != nil {
fmt.Fprintf(os.Stderr, "error reading %s: %v\n", filename, err)
os.Exit(1)
}
} else {
input, err = io.ReadAll(os.Stdin)
if err != nil {
fmt.Fprintf(os.Stderr, "error reading stdin: %v\n", err)
os.Exit(1)
}
}
var parsed interface{}
if err := json.Unmarshal(input, &parsed); err != nil {
fmt.Fprintf(os.Stderr, "invalid JSON: %v\n", err)
os.Exit(1)
}
if *validate {
fmt.Fprintln(os.Stderr, "valid JSON")
os.Exit(0)
}
if *sortKeys {
parsed = sortMapKeys(parsed)
}
var output []byte
if *compact {
output, err = json.Marshal(parsed)
} else {
indentStr := ""
for i := 0; i < *indent; i++ {
indentStr += " "
}
output, err = json.MarshalIndent(parsed, "", indentStr)
}
if err != nil {
fmt.Fprintf(os.Stderr, "error formatting: %v\n", err)
os.Exit(1)
}
output = append(output, '\n')
if *write && filename != "" {
if bytes.Equal(input, output) {
return
}
if err := os.WriteFile(filename, output, 0644); err != nil {
fmt.Fprintf(os.Stderr, "error writing %s: %v\n", filename, err)
os.Exit(1)
}
return
}
os.Stdout.Write(output)
}
func sortMapKeys(v interface{}) interface{} {
switch val := v.(type) {
case map[string]interface{}:
keys := make([]string, 0, len(val))
for k := range val {
keys = append(keys, k)
}
sort.Strings(keys)
sorted := make(map[string]interface{}, len(val))
for _, k := range keys {
sorted[k] = sortMapKeys(val[k])
}
return sorted
case []interface{}:
for i, item := range val {
val[i] = sortMapKeys(item)
}
return val
default:
return v
}
}