Go - JSON Encoding/Decoding
Beginner 10/10
Teacher 10/10
Architect 10/10
Try it: Create a struct with JSON tags and
json.Marshal
it; print the string.Marshal
type User struct{ ID int `json:"id"`; Name string `json:"name"` }
u := User{ID:1, Name:"Alice"}
b, _ := json.Marshal(u) // {"id":1,"name":"Alice"}
Unmarshal
var u User
_ = json.Unmarshal([]byte(`{"id":2,"name":"Bob"}`), &u)
Streams
json.NewEncoder(w).Encode(u)
json.NewDecoder(r.Body).Decode(&u)
Common errors
- Unexported (lowercase) fields won’t be marshaled—export fields by capitalizing.
- Forgetting
Content-Type: application/json
when writing HTTP responses.
Practice
- Decode JSON from a string into a struct; handle decode errors.
Quick quiz
- What do struct tags like
json:"name"
do?