CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

main.go
package main

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

func main() {
    // buraya yaz
}

Sample solution

main.go
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)
    }
}

Expected output

a
b

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is best for reading a line-by-line JSON (NDJSON) stream?

  • Decoding each object in turn with dec.Decode in a loop Correct answer
  • Reading everything with ReadAll and calling Unmarshal
  • Splitting with strings.Split
  • Using an Encoder

Explanation: A Decoder reads the next complete JSON value from the stream; looping until io.EOF processes the whole stream with constant memory.

2 Decode the body

Question
if err := json.NewDecoder(r.Body).____(&istek); err != nil {
    return err
}
Answer
if err := json.NewDecoder(r.Body).Decode(&istek); err != nil {
    return err
}

Explanation: Decoder.Decode decodes the next JSON value in the stream into the target.

3 Tool and use

Term Meaning
json.Marshal Produces bytes in memory
json.NewEncoder Streams to a Writer
json.NewDecoder Reads from a Reader
SetIndent Readable output

All lessons in Intermediate