Stream a JSON Array with an Encoder
Encode a large result set incrementally with json.Encoder and a buffered writer instead of marshalling the whole slice at once.
Code
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"strings"
"time"
)
type Row struct {
ID int `json:"id"`
Message string `json:"message"`
At time.Time `json:"at"`
}
func StreamJSONArray(w io.Writer, rows <-chan Row) error {
buffered := bufio.NewWriter(w)
encoder := json.NewEncoder(buffered)
encoder.SetEscapeHTML(false)
if _, err := buffered.WriteString("["); err != nil {
return err
}
first := true
for row := range rows {
if !first {
if _, err := buffered.WriteString(","); err != nil {
return err
}
}
if err := encoder.Encode(row); err != nil {
return err
}
first = false
}
if _, err := buffered.WriteString("]"); err != nil {
return err
}
return buffered.Flush()
}
func main() {
rows := make(chan Row, 3)
at := time.Date(2026, 10, 21, 9, 0, 0, 0, time.UTC)
for i := 1; i <= 3; i++ {
rows <- Row{ID: i, Message: fmt.Sprintf("row %d", i), At: at.Add(time.Duration(i) * time.Minute)}
}
close(rows)
var out strings.Builder
if err := StreamJSONArray(&out, rows); err != nil {
fmt.Println("encode:", err)
return
}
fmt.Println(out.String())
}
How it works
Stream a JSON Array with an Encoder keeps everything in the functions StreamJSONArray and main.
Repetition is confined to for row := range rows — the rest of the file is straight-line. Every fallible call checks err != nil (5 sites), so an error is handled where it happens rather than bubbling invisibly.
Watch out for
- Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Putting it to use
The primary signature is func StreamJSONArray(w io.Writer, rows <-chan Row) error
Look for the encode: prefixes when the file runs; they tie each line to its step.
main is the driver: it invokes StreamJSONArray before returning.
The core lines, annotated
rows <- Row{ID: i, Message: fmt.Sprintf("row %d", i), At: at.Add(time.Duration(i) * time.Minute)}
for row := range rows {
if !first {
if _, err := buffered.WriteString(","); err != nil {
return err
}
}
if err := encoder.Encode(row); err != nil {
return err
}
first = false
}
rows := make(chan Row, 3)
Interactive Tools for This Topic
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
FAQ
- How do errors reach the caller?
- The Go way: `err` comes back from each call, and 5 checkpoints here test it before proceeding.
- What does Stream a JSON Array with an Encoder print when run?
- No setup needed: run the file and look for labeled lines like `encode:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.