-
Notifications
You must be signed in to change notification settings - Fork 2
/
json.go
57 lines (45 loc) · 847 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
48
49
50
51
52
53
54
55
56
57
package bkl
import (
"bytes"
"encoding/json"
"errors"
"io"
)
func jsonMarshalStream(vs []any) ([]byte, error) {
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
for _, v := range vs {
err := enc.Encode(v)
if err != nil {
return nil, err
}
}
return buf.Bytes(), nil
}
func jsonMarshalStreamPretty(vs []any) ([]byte, error) {
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetIndent("", " ")
for _, v := range vs {
err := enc.Encode(v)
if err != nil {
return nil, err
}
}
return buf.Bytes(), nil
}
func jsonUnmarshalStream(in []byte) ([]any, error) {
dec := json.NewDecoder(bytes.NewReader(in))
ret := []any{}
for {
var obj any
err := dec.Decode(&obj)
if errors.Is(err, io.EOF) {
break
} else if err != nil {
return nil, err
}
ret = append(ret, obj)
}
return ret, nil
}