-
Notifications
You must be signed in to change notification settings - Fork 6
/
json.go
86 lines (75 loc) · 1.47 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
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
package enc
import (
"bytes"
"encoding/json"
"github.com/Aize-Public/forego/ctx"
)
func MustMarshal(c ctx.C, from any) Node {
n, err := Marshal(c, from)
if err != nil {
panic(err)
}
return n
}
func MustMarshalJSON(c ctx.C, from any) []byte {
n, err := Marshal(c, from)
if err != nil {
panic(err)
}
return JSON{
//Indent: true, // NOTE(oha): fixme
}.Encode(c, n)
}
func MarshalJSON(c ctx.C, from any) ([]byte, error) {
n, err := Marshal(c, from)
if err != nil {
return nil, err
}
return JSON{}.Encode(c, n), nil
}
func UnmarshalJSON(c ctx.C, j []byte, into any) error {
n, err := JSON{}.Decode(c, j)
if err != nil {
return err
}
return Unmarshal(c, n, into)
}
type JSON struct {
Indent bool
}
var _ Codec = JSON{}
func (this JSON) Encode(c ctx.C, n Node) []byte {
if this.Indent {
j, err := json.MarshalIndent(n, "", " ")
if err != nil {
panic(err)
}
return j
} else {
j, err := json.Marshal(n)
if err != nil {
panic(err)
}
return j
}
}
func mustJSON(in any) []byte {
j, err := json.Marshal(in)
if err != nil {
panic(err)
}
return j
}
func (this JSON) Decode(c ctx.C, data []byte) (Node, error) {
if len(data) == 0 {
return nil, nil // NOTE(oha): we don't want to give error for empty or nil data
}
var obj any
dec := json.NewDecoder(bytes.NewBuffer(data))
dec.UseNumber()
err := dec.Decode(&obj)
if err != nil {
return nil, ctx.NewErrorf(ctx.WithTag(c, "data", string(data)), "%w", err)
}
return fromNative(obj), nil
}