Go NDJSON Streaming with json.Decoder
Decode newline-delimited JSON events one at a time with json.Decoder, validate each record, and aggregate without buffering the file.
Code
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
)
type Event struct {
ID int `json:"id"`
Type string `json:"type"`
AmountCents int64 `json:"amount_cents"`
Meta map[string]string `json:"meta,omitempty"`
}
func streamNDJSON(r io.Reader, handle func(Event) error) error {
decoder := json.NewDecoder(r)
for {
var event Event
if err := decoder.Decode(&event); err != nil {
if errors.Is(err, io.EOF) {
return nil
}
return fmt.Errorf("decode event: %w", err)
}
if event.ID <= 0 {
return fmt.Errorf("event %d: id must be positive", event.ID)
}
if event.Type == "" {
return fmt.Errorf("event %d: type is required", event.ID)
}
if event.AmountCents < 0 {
return fmt.Errorf("event %d: amount_cents must be >= 0", event.ID)
}
if err := handle(event); err != nil {
return err
}
}
}
func main() {
payload := strings.Join([]string{
`{"id":1,"type":"credit","amount_cents":1250}`,
`{"id":2,"type":"debit","amount_cents":325,"meta":{"channel":"api"}}`,
`{"id":3,"type":"credit","amount_cents":900}`,
}, "\n")
var netCents int64
counts := map[string]int{}
err := streamNDJSON(strings.NewReader(payload), func(event Event) error {
counts[event.Type]++
if event.Type == "credit" {
netCents += event.AmountCents
} else {
netCents -= event.AmountCents
}
return nil
})
fmt.Printf("counts=%v net_cents=%d err=%v\n", counts, netCents, err)
bad := bytes.NewBufferString("{\"id\":4,\"type\":\"credit\",\"amount_cents\":500}\n{\"id\":5,\"amount_cents\":100}\n")
seen := 0
err = streamNDJSON(bad, func(Event) error {
seen++
return nil
})
fmt.Printf("seen=%d err=%v\n", seen, err)
}How it works
Under the hood: the functions streamNDJSON and main.
Repetition is confined to for — the rest of the file is straight-line. Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly.
Points of care
- 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 streamNDJSON(r io.Reader, handle func(Event) error) error
Running the file prints labeled results such as counts=, seen= — each operation’s effect is visible in the output.
main sequences streamNDJSON; executing the file runs that flow once.
Core lines under the microscope
return fmt.Errorf("decode event: %w", err)
return fmt.Errorf("event %d: amount_cents must be >= 0", event.ID)
return fmt.Errorf("event %d: id must be positive", event.ID)
Interactive Tools for This Topic
JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.NDJSON to JSON ConverterTurn newline-delimited JSON (JSON Lines) into a single JSON array, reporting the exact line where parsing fails.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.
FAQ
- How does the code signal failure?
- No exceptions — `error` returns checked at 2 sites, and callers branch on `err` first.
- What does Go NDJSON Streaming with json.Decoder print when run?
- The script runs standalone; its 2 labeled outputs include `counts=`, `seen=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.