-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
51 lines (46 loc) · 1.3 KB
/
json.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
package gosh
import (
"encoding/json"
"io"
)
// JSONDecoderOptions are options to provide to an encoding/json.Decoder
type JSONDecoderOptions struct {
UseNumber bool
DisallowUnknownFields bool
}
// SaveJSON returns a PipeSink which decodes JSON-encoded output and stores it in the value pointed to by v . See encoding/json for rules on how this works.
func SaveJSON(v interface{}, opts ...JSONDecoderOptions) PipeSink {
return func(r io.Reader) error {
dec := json.NewDecoder(r)
for _, opt := range opts {
if opt.UseNumber {
dec.UseNumber()
}
if opt.DisallowUnknownFields {
dec.DisallowUnknownFields()
}
}
return dec.Decode(v)
}
}
// JSONEncoderOptions are options to provide to an encoding/json.Encoder
type JSONEncoderOptions struct {
IndentString string
IndentPrefix string
HTMLEscape bool
}
// JSONIn returns a PipeSource which provides the JSON encoding of v. See encoding/json for rules on how this works.
func JSONIn(v interface{}, opts ...JSONEncoderOptions) PipeSource {
return func(w io.Writer) error {
enc := json.NewEncoder(w)
for _, opt := range opts {
if opt.IndentString != "" || opt.IndentPrefix != "" {
enc.SetIndent(opt.IndentPrefix, opt.IndentString)
}
if opt.HTMLEscape {
enc.SetEscapeHTML(true)
}
}
return enc.Encode(v)
}
}