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
}