Streaming JSON Decoder Over a Reader
Decode a stream of JSON values from a reader without buffering the whole payload, using a decoder that reads records one at a time.
Code
package main
import (
"encoding/json"
"fmt"
"io"
"strings"
)
type Event struct {
Type string `json:"type"`
ID int `json:"id"`
}
func decodeStream(stream io.Reader) ([]Event, error) {
decoder := json.NewDecoder(stream)
var events []Event
for {
var event Event
if err := decoder.Decode(&event); err != nil {
if err == io.EOF {
break
}
return nil, fmt.Errorf("decode: %w", err)
}
events = append(events, event)
}
return events, nil
}
func main() {
input := strings.NewReader("{"type":"a","id":1}
{"type":"b","id":2}
")
events, err := decodeStream(input)
if err != nil {
panic(err)
}
fmt.Println(events)
}How it works
Streaming JSON Decoder Over a Reader keeps everything in the functions decodeStream and main.
Iteration happens inside for — everything outside it runs once. Failures are values here: 2 sites check err and decide instead of letting one propagate.
Watch out for
- Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Using it
The main signature reads func decodeStream(stream io.Reader) ([]Event, error)
There are 1 call inside main — decodeStream — executed top to bottom.
Key statements
return nil, fmt.Errorf("decode: %w", err)
if err != nil {
panic(err)
}
events = append(events, event)
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 should callers handle failures?
- Through `error` values — the snippet checks `err != nil` at 2 sites, and the entry flow turns failures into `panic(err)`.
- How do you run Streaming JSON Decoder Over a Reader?
- Direct execution is enough; the script has no external requirements.
Report a problem with this exampleOpens a pre-filled issue on GitHub.