encoding/json marshals structs to JSON and unmarshals back—field tags control names: `json:"name"`. Essential for REST APIs and Kubernetes manifests.
Marshal and Unmarshal
type User struct {
Name string `json:"name"`
}
b, _ := json.Marshal(User{Name: "Ada"})
var u User
json.Unmarshal(b, &u)
Exported fields only—unexported fields are ignored. Use json.RawMessage for deferred parsing.
Important interview questions and answers
- Q: Why pointer to Unmarshal target?
A: Unmarshal must modify the value—pass&struct. - Q: omitempty tag?
A: Omits field when zero value—smaller API payloads.
Self-check
- What tag renames a JSON field?
- Why must JSON fields be exported?
Pitfall: Unexported struct fields are invisible to encoding/json—capitalize field names or use custom MarshalJSON.
Interview prep
- Why pointer to Unmarshal?
Unmarshal must modify the destination value—pass address of struct.
- json tag omitempty?
Omits field when zero value—smaller API payloads.