-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
47 lines (40 loc) · 939 Bytes
/
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
package encoding
import (
"encoding/json"
)
//-------------------------
// ToJson encode a Go data to json string
func ToJson(v interface{}, pretty bool) (string, error) {
var b []byte
var err error
if pretty {
b, err = json.MarshalIndent(v, "", " ")
} else {
b, err = json.Marshal(v)
}
return unsafeByteString(b), err
}
// MustToJson encode a Go data to json string.
// It panic if error.
func MustToJson(v interface{}, pretty bool) string {
s, err := ToJson(v, pretty)
if err != nil {
panic(err)
}
return s
}
// FromJson decode a json string to universal Go data
func FromJson(s string) (interface{}, error) {
var d interface{}
err := json.Unmarshal(unsafeStringBytes(s), &d) // decode to *interface{}
return d, err
}
// MustFromJson decode a json string to universal Go data.
// It panic if error.
func MustFromJson(s string) interface{} {
d, err := FromJson(s)
if err != nil {
panic(err)
}
return d
}