Daaang Amy
open main menu

Go JSON Encoding and Decoding

/ 1 min read

JSON Encoding

There are two ways to do encode JSON in Go. With Go’s encoding/json package we can:

  1. call json.Marshal()
  2. declare and a json.Encoder

Either way could work but there is a small problem with using json.Encoder. When using the json.Encoder, the JSON is created and writes to http.ResponseWriter within a single step. This means that there will be no opportunity to neither check for an error response nor add response headers.

JSON Decoding

Like JSON encoding, there are two ways to do this:

  1. call json.Unmarshal()
  2. use json.Decoder

In this case, using json.Unmarshal is less efficient and more verbose than using json.Decoder.

Using json.Unmarshal()

func handler(w http.ResponseWriter, r *http.Request) {
  // Using json.Unmarshal
  var input struct {
    Foo string `json:"foo"`
  }

  body, err := io.ReadAll(r.Body)
  if err != nil {
    app.serverErrorResponse(w, r, err)
    return
  }

  err = json.Unmarshal(body, &input)
  if err != nil {
    app.errorResponse(w, r, http.StatusBadRequest, err.Error())
    return
  }
  fmt.Fprintf(w, "%+v\n", input
}

Using json.Decoder

func handler(w http.ResponseWriter, r *http.Request) {
  var input struct {
    Foo string `json:"foo"`
  }

  err := json.NewDecoder(r.Body).Decode(&input)
  if err != nil {
    app.errorResponse(w, r, http.StatusBadRequest, err.Error())
  }
}