json.Encoder / Decoder
json.Encoder and json.Decoder read and write JSON to and from a stream. By combining them with io.Writer / io.Reader (such as files or network connections), you can process data with efficient memory usage.
Syntax
// Create an Encoder and write a value as JSON enc := json.NewEncoder(writer) err := enc.Encode(value) // Create a Decoder and decode JSON from a reader dec := json.NewDecoder(reader) err := dec.Decode(&v)
Function List
| Function / Method | Description |
|---|---|
| json.NewEncoder(w) | Creates an Encoder that wraps an io.Writer. |
| enc.Encode(v) | JSON-encodes v and writes it to the Writer. A newline is appended automatically at the end. |
| enc.SetIndent(prefix, indent) | Configures the output of Encode() to use indentation. |
| json.NewDecoder(r) | Creates a Decoder that wraps an io.Reader. |
| dec.Decode(v) | Reads JSON from the Reader and decodes it into v. |
| dec.More() | Reports whether there is another element in the current array or object. |
Sample Code
package main
import (
"encoding/json"
"fmt"
"os"
"strings"
)
type Product struct {
Name string `json:"name"`
Price float64 `json:"price"`
}
func main() {
// Write JSON directly to standard output using an Encoder
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
products := []Product{
{Name: "Apple", Price: 150},
{Name: "Orange", Price: 80},
}
fmt.Println("--- Encoder output ---")
enc.Encode(products)
// Decode a JSON string using a Decoder
jsonData := `
{"name":"Grape","price":300}
{"name":"Peach","price":250}
`
dec := json.NewDecoder(strings.NewReader(jsonData))
fmt.Println("--- Decoder input ---")
for dec.More() {
var p Product
if err := dec.Decode(&p); err != nil {
fmt.Println("Decode error:", err)
break
}
fmt.Printf("%s: %.0f\n", p.Name, p.Price)
}
}
Output
--- Encoder output ---
[
{
"name": "Apple",
"price": 150
},
{
"name": "Orange",
"price": 80
}
]
--- Decoder input ---
Grape: 300
Peach: 250
Notes
Because Encoder / Decoder work directly with io.Writer / io.Reader, you can read from and write to HTTP responses or files without any intermediate buffer. When working with large JSON data, they are more memory-efficient than json.Marshal / Unmarshal.
When returning JSON from an HTTP handler, json.NewEncoder(w).Encode(data) is the standard pattern. Note that enc.Encode() automatically appends a newline at the end. Keep this in mind if you need precise control over the JSON stream.
If you find any errors or copyright issues, please contact us.