-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson.go
More file actions
52 lines (44 loc) · 1.07 KB
/
json.go
File metadata and controls
52 lines (44 loc) · 1.07 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
package u
import (
"encoding/json"
"fmt"
"io"
"strings"
)
func JSONTuplesPretty(args ...string) string {
w := &strings.Builder{}
fmt.Fprintf(w, "{\n")
for i := 0; i < len(args)-1; i += 2 {
key := args[i]
val := args[i+1]
fmt.Fprintf(w, "\t%q: %q,\n", key, val)
}
key := args[len(args)-2]
val := args[len(args)-1]
fmt.Fprintf(w, "\t%q: %q\n}", key, val)
return w.String()
}
// JSONTuples creates a marshalable JSON string by treating even-indexed args
// as keys and odd-indexed args as values.
func JSONTuples(args ...string) string {
w := &strings.Builder{}
fmt.Fprintf(w, "{")
for i := 0; i < len(args)-1; i += 2 {
key := args[i]
val := args[i+1]
fmt.Fprintf(w, "%q:%q,", key, val)
}
key := args[len(args)-2]
val := args[len(args)-1]
fmt.Fprintf(w, "%q:%q}", key, val)
return w.String()
}
// PrettyJSON reads from r and writes to w, priting nicely formatted JSON.
func PrettyJSON(r io.Reader, w io.Writer) {
var m map[string]any
dec := json.NewDecoder(r)
Must(dec.Decode(&m))
enc := json.NewEncoder(w)
enc.SetIndent("", "\t")
Must(enc.Encode(m))
}