JSON

JSON is quickly becoming the ubiquitous serialization format for web APIs, so
it may be the most relevant when learning how to build web apps
using Go. Fortunately, Go makes it simple to work with JSON — it is
extremely easy to turn existing Go structs into JSON using the encoding/json
package from the standard library.

  1. package main
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. )
  6. type Book struct {
  7. Title string `json:"title"`
  8. Author string `json:"author"`
  9. }
  10. func main() {
  11. http.HandleFunc("/", ShowBooks)
  12. http.ListenAndServe(":8080", nil)
  13. }
  14. func ShowBooks(w http.ResponseWriter, r *http.Request) {
  15. book := Book{"Building Web Apps with Go", "Jeremy Saenz"}
  16. js, err := json.Marshal(book)
  17. if err != nil {
  18. http.Error(w, err.Error(), http.StatusInternalServerError)
  19. return
  20. }
  21. w.Header().Set("Content-Type", "application/json")
  22. w.Write(js)
  23. }

Exercises

  1. Read through the JSON API docs and find out how to rename and ignore fields for JSON serialization.
  2. Instead of using the json.Marshal method, try using the json.Encoder API.
  3. Figure our how to pretty print JSON with the encoding/json package.