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.

GoData Fetching

Code

gosnippet
59 lines
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 err before 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

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.