How to Stream JSON with json.Decoder and json.Encoder

Stream JSON data in Go using json.Decoder and json.Encoder to process large payloads sequentially without loading them entirely into memory.

Use json.Decoder to read JSON values sequentially from an io.Reader and json.Encoder to write them sequentially to an io.Writer without loading the entire payload into memory.

package main

import (
	"encoding/json"
	"fmt"
	"io"
	"strings"
)

func main() {
	// Streaming Decode
	reader := strings.NewReader(`{"id":1,"name":"Alice"}{"id":2,"name":"Bob"}`)
	dec := json.NewDecoder(reader)
	for {
		var item map[string]interface{}
		if err := dec.Decode(&item); err == io.EOF {
			break
		}
		if err != nil {
			fmt.Println("Error:", err)
			break
		}
		fmt.Println("Decoded:", item)
	}

	// Streaming Encode
	var writer strings.Builder
	enc := json.NewEncoder(&writer)
	items := []map[string]interface{}{{"id": 1}, {"id": 2}}
	for _, item := range items {
		if err := enc.Encode(item); err != nil {
			fmt.Println("Error:", err)
			return
		}
	}
	fmt.Println("Encoded:", writer.String())
}