Go
Encoder and Decoder
Learn json.NewEncoder and json.NewDecoder.
Encoder and Decoder
json.NewEncoder(w) and json.NewDecoder(r) work directly with a Writer/Reader; no intermediate []byte is needed. In HTTP they are the standard way to read the body and write the response:
var istek YeniUrun
if err := json.NewDecoder(r.Body).Decode(&istek); err != nil {
http.Error(w, "geçersiz JSON", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(sonuc)
Encode appends a newline after every value.
Settings
Decoder and Encoder behavior can be adjusted:
dec := json.NewDecoder(r)
dec.DisallowUnknownFields() // unknown key → error
dec.UseNumber() // numbers as json.Number instead of float64
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ") // readable output
enc.SetEscapeHTML(false) // don't escape < > &
In APIs that want strict validation, DisallowUnknownFields catches misspelled fields early.
Exercise Read NDJSON
Create a two-line stream with strings.NewReader: {"ad":"a"} and {"ad":"b"}. Decode it in a loop with json.NewDecoder, stop on io.EOF and print each name.
Show example solution
package main
import (
"encoding/json"
"fmt"
"io"
"strings"
)
func main() {
dec := json.NewDecoder(strings.NewReader("{\"ad\":\"a\"}\n{\"ad\":\"b\"}\n"))
for {
var v struct {
Ad string `json:"ad"`
}
if err := dec.Decode(&v); err == io.EOF {
break
} else if err != nil {
fmt.Println(err)
return
}
fmt.Println(v.Ad)
}
}
Test yourself
-
Which is best for reading a line-by-line JSON (NDJSON) stream?
- Decoding each object in turn with dec.Decode in a loop
- Reading everything with ReadAll and calling Unmarshal
- Splitting with strings.Split
- Using an Encoder
Show answer
Decoding each object in turn with dec.Decode in a loop — A Decoder reads the next complete JSON value from the stream; looping until io.EOF processes the whole stream with constant memory.
-
Decode the body
if err := json.NewDecoder(r.Body).____(&istek); err != nil {
return err
}
Show answer
if err := json.NewDecoder(r.Body).Decode(&istek); err != nil {
return err
}
-
Tool and use
- json.Marshal
- Produces bytes in memory
- json.NewEncoder
- Streams to a Writer
- json.NewDecoder
- Reads from a Reader
- SetIndent
- Readable output
Next lesson: JSON and map