-
Notifications
You must be signed in to change notification settings - Fork 19
/
json.go
54 lines (44 loc) · 1.26 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
52
53
54
package utils
import (
"bytes"
"encoding/json"
)
// JSONMarshal marshals the given object to JSON
func JSONMarshal(v interface{}) ([]byte, error) {
return jsonMarshal(v, "")
}
// JSONMarshalPretty marshals the given object to pretty JSON
func JSONMarshalPretty(v interface{}) ([]byte, error) {
return jsonMarshal(v, " ")
}
func jsonMarshal(v interface{}, indent string) ([]byte, error) {
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false) // see https://github.com/golang/go/issues/8592
encoder.SetIndent("", indent)
err := encoder.Encode(v)
if err != nil {
return nil, err
}
// don't include the final \n that .Encode() adds
data := buffer.Bytes()
return data[0 : len(data)-1], nil
}
// UnmarshalAndValidate is a convenience function to unmarshal an object and validate it
func UnmarshalAndValidate(data []byte, obj interface{}, objName string) error {
err := json.Unmarshal(data, obj)
if err != nil {
return err
}
err = ValidateAs(obj, objName)
if err != nil {
return err
}
return nil
}
// UnmarshalArray unmarshals an array of objects from the given JSON
func UnmarshalArray(data json.RawMessage) ([]json.RawMessage, error) {
var items []json.RawMessage
err := json.Unmarshal(data, &items)
return items, err
}