Understanding Go JSON Struct Tags
Deep dive into Go json struct tags including field naming, omitempty, string option, and dash to ignore fields. Essential for JSON serialization control.
Detailed Explanation
Go JSON Struct Tags Explained
Struct tags are the key mechanism Go uses to control JSON serialization and deserialization. The json tag is placed after the field type inside backticks.
Tag Syntax
type Config struct {
Name string `json:"name"`
Version int `json:"version"`
Debug bool `json:"debug,omitempty"`
Internal string `json:"-"`
Count string `json:"count,string"`
}
Tag Options
| Option | Meaning |
|---|---|
json:"name" |
Map this field to JSON key "name" |
json:"name,omitempty" |
Omit from output if the field has its zero value |
json:"-" |
Always ignore this field during marshal/unmarshal |
json:"count,string" |
Encode/decode a number or bool as a JSON string |
json:",omitempty" |
Use the field name as-is but omit when empty |
Why Tags Matter
Without tags, Go uses the field name directly as the JSON key. Since Go fields must be exported (uppercase), you would get "Name" instead of "name" in your JSON output. Tags let you match the exact casing and naming of the API you are consuming or producing.
The string Option
Some APIs send numbers as strings: "count": "42". The string option handles this transparently:
Count int `json:"count,string"`
This tells encoding/json to expect a JSON string and parse the number inside it.
Combining Options
You can combine omitempty and string:
Price float64 `json:"price,omitempty,string"`
Understanding struct tags is critical for correct JSON handling in Go. They are the bridge between Go's type system and the flexible world of JSON.
Use Case
Every Go project that interacts with JSON APIs needs struct tags. They are essential for matching field names to API contracts, hiding internal fields, and handling edge cases like numeric strings.