Lesson 19 of 60 · Go
JSON Marshalling & Unmarshalling
Duration: 20 minutes
JSON in Go
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
The encoding/json package provides Marshal and Unmarshal.
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Age int `json:"age,omitempty"`
}
u := User{ID: 1, Name: "Alice"}
bytes, _ := json.Marshal(u)
fmt.Println(string(bytes)) // {"id":1,"name":"Alice"}
Decoding from a request body
func createUser(w http.ResponseWriter, r *http.Request) {
var u User
if err := json.NewDecoder(r.Body).Decode(&u); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// process u …
w.WriteHeader(http.StatusCreated)
}
Custom Marshal/Unmarshal
Implement the json.Marshaler and json.Unmarshaler interfaces for special handling.