我想用它json.Encoder
来编码大量数据流,而不是一次将所有数据加载到内存中。
// I want to marshal this
t := struct {
Foo string
// Bar is a stream of objects
// I don't want it all to be in memory at the same time.
Bar chan string
}{
Foo: "Hello World",
Bar: make(chan string),
}
// long stream of data
go func() {
for _, x := range []string{"one", "two", "three"} {
t.Bar <- x
}
close(t.Bar)
}()
我想也许 json 包内置了这个功能,但事实并非如此。
// error: json: unsupported type: chan string
if err := json.NewEncoder(os.Stdout).Encode(&t); err != nil {
log.Fatal(err)
}
我目前只是自己构建 json 字符串。
w := os.Stdout
w.WriteString(`{ "Foo": "` + t.Foo + `", "Bar": [`)
for x := range t.Bar {
_ = json.NewEncoder(w).Encode(x)
w.WriteString(`,`)
}
w.WriteString(`]}`)
有一个更好的方法吗?
如果json.Marshaler是这样的,那将是微不足道的。
type Marshaler interface {
MarshalJSON(io.Writer) error
}