Struct Tags
Writing a Struct Tag
A struct tag is a raw string (written between backticks) placed after a field's type, conventionally holding space-separated key:"value" pairs that libraries like encoding/json read via reflection.
Example: Writing a Struct Tag
package main
import "fmt"
type Product struct {
Name string `json:"name"`
Price float64 `json:"price"`
}
func main() {
p := Product{Name: "Notebook", Price: 3.5}
fmt.Printf("%+v\n", p)
}
Login to try C/C++/Java/PHP code in the editor
Using Tags with encoding/json
The json tag controls exactly what key name is used when a struct is converted to JSON, letting you follow Go's exported-field naming convention (Name) while producing lowercase JSON keys ("name") that match common API conventions.
Note: Only capitalized (exported) fields are ever visible to encoding/json.
Example: Using Tags with encoding/json
package main
import (
"encoding/json"
"fmt"
)
type Product struct {
Name string `json:"name"`
Price float64 `json:"price"`
}
func main() {
p := Product{Name: "Notebook", Price: 3.5}
data, _ := json.Marshal(p)
fmt.Println(string(data))
}
Login to try C/C++/Java/PHP code in the editor
Omitting Empty Fields
Adding ',omitempty' to a json tag tells the encoder to skip that field entirely in the output when it holds its zero value, which keeps generated JSON compact when many fields are optional.
Example: Omitting Empty Fields
package main
import (
"encoding/json"
"fmt"
)
type Product struct {
Name string `json:"name"`
Note string `json:"note,omitempty"`
}
func main() {
p := Product{Name: "Pen"}
data, _ := json.Marshal(p)
fmt.Println(string(data))
}
Login to try C/C++/Java/PHP code in the editor
- Getting the backtick-quoted tag string syntax wrong (mismatched quotes inside), which silently causes the tag to be ignored rather than erroring.
- Forgetting a struct field must be exported (capitalized) for encoding/json to see it at all, regardless of its tag.
- Misspelling a tag key like json as JSON, which reflection-based libraries won't recognize.
- A struct tag is a string literal attached to a field, written in backticks after its type.
- encoding/json reads
json:"name"tags to control the field name and behavior during marshaling. - Only exported (capitalized) fields are visible to encoding/json regardless of tags.
- Tags are read at runtime via reflection -- they have no effect on how the Go compiler treats the field.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: