-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathjson.go
More file actions
46 lines (40 loc) · 1.03 KB
/
json.go
File metadata and controls
46 lines (40 loc) · 1.03 KB
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
package jsonutil
import (
"encoding/json"
"io"
)
// JSONArrayWriter writes out a result as a JSON array in incremental fashion
type JSONArrayWriter struct {
prependComma bool
writer io.Writer
encoder *json.Encoder
}
// NewJSONArrayWriter takes in an output writer and creates a new JSONArrayWriter
func NewJSONArrayWriter(writer io.Writer) *JSONArrayWriter {
return &JSONArrayWriter{
prependComma: false,
writer: writer,
encoder: json.NewEncoder(writer),
}
}
// Init writes a [ to the writer
func (j *JSONArrayWriter) Init() error {
_, err := j.writer.Write([]byte("["))
return err
}
// WriteObject writes an interface into JSON and writes it to the writer
func (j *JSONArrayWriter) WriteObject(i interface{}) error {
if !j.prependComma {
j.prependComma = true
} else {
if _, err := j.writer.Write([]byte(",")); err != nil {
return err
}
}
return j.encoder.Encode(i)
}
// Finish finishes the array with a ]
func (j *JSONArrayWriter) Finish() error {
_, err := j.writer.Write([]byte("]"))
return err
}