JSON tags
A JSON tag is a struct tag on a field that tells encoding/json the key name and options: `json:"name,omitempty"`. Unexported fields are skipped even with a tag.
Detailed Explanation
By default, json.Marshal uses the exported field name as the key: UserID becomes "UserID". APIs usually want "user_id" or "userId". The tag sets that name. Options after a comma change behaviour: omitempty drops empty values, - skips the field, omitzero (Go 1.24+) drops zeros more consistently, string encodes a number as a JSON string.
Empty means the type's zero. omitempty treats 0, "", nil, and false as empty. A 0 port you must send should not use omitempty, or should be a *int. This is the usual API bug: optional numbers vs "not provided."
Embedded structs. Exported anonymous structs are inlined into the parent object unless you give the field a name. Tags on the embedded field (json:",inline" is not required for structs — they inline by default) vs a named field (Profile Profile \json:"profile"``) decide flattening.
Unknown fields. Decoder.DisallowUnknownFields() rejects extra keys. The default ignores them. Pick one for request bodies and document it.
What it costs. Tags are reflection metadata. Marshal/unmarshal already uses reflection; the tag is not an extra tax you feel. The maintenance cost is keeping tags in sync with the API spec. Regenerating types from OpenAPI is one way; a golden JSON test is another.
Code Examples
package main
import (
"encoding/json"
"fmt"
)
type User struct {
ID int64 `json:"id"`
Name string `json:"name"`
Email string `json:"email,omitempty"`
pass string `json:"pass"` // still omitted: unexported
}
func main() {
b, _ := json.Marshal(User{ID: 1, Name: "Ada"})
fmt.Println(string(b)) // {"id":1,"name":"Ada"}
}type Port struct {
N *int `json:"port,omitempty"` // distinguish missing from 0
}Common Gotchas
`omitempty` on `int` hides `0`
use a pointer if 0 is valid and optional.
A tag does not export a lowercase field
`encoding/json` will not see it.
`Decoder` is not `Unmarshal`
stream options live on the decoder.