patterngoTip
JSON struct tags for encoding/decoding control
Viewed 0 times
json struct tagsomitemptyjson marshaljson unmarshalstruct tagsencoding/jsonfield naming
Problem
Without struct tags, Go exports struct fields using their exact name (PascalCase), which doesn't match the snake_case or camelCase conventions expected by JSON APIs.
Solution
Use json struct tags to control field names and behaviour:
type User struct {
ID int `json:"id"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Password string `json:"-"` // never marshaled
CreatedAt time.Time `json:"created_at,omitempty"` // omit if zero
Internal string `json:"internal,omitempty"`
}
// Marshal
data, err := json.Marshal(user)
// Unmarshal
err = json.Unmarshal(data, &user)
// Use json.NewDecoder for streams (HTTP bodies)
err = json.NewDecoder(r.Body).Decode(&user)Why
The encoding/json package reads struct tags at runtime via reflection. The tag syntax is
json:"name,options" where options include omitempty and string.Gotchas
- json:"-" means the field is always skipped; json:"-," (with comma) means the JSON key is literally "-"
- omitempty omits the field if it is the zero value — for pointers, the zero is nil; for structs, it's an empty struct (never omitted unless pointer)
- Unexported fields are always ignored by encoding/json regardless of tags
Revisions (0)
No revisions yet.