Struct tags
- Go course
- Intermediate
- Lesson 60/80
- 4 min
Learn to control field names with json:"..." tags.
Struct tags
JSON field names are usually lower case. A struct tag maps the Go field name to a JSON name and adds options:
type Kullanici struct {
ID int `json:"id"`
Ad string `json:"ad"`
Eposta string `json:"eposta,omitempty"`
Sifre string `json:"-"`
}omitempty drops a zero-valued field from the output; - always skips the field (for secrets such as passwords).
Tag syntax
Tags are key:"value" pairs inside backticks; several libraries can use their own key on the same field:
Ad string `json:"ad" db:"ad_soyad" validate:"required"`When decoding (Unmarshal), JSON keys are matched to tags case-insensitively. Unknown keys are silently ignored; to reject them use Decoder.DisallowUnknownFields().
Practice Tagged encoding
Write type User struct: ID int → "id", Name string → "name", Email string → "email,omitempty", Password string → "-". Encode User{ID: 1, Name: "Ada", Password: "x"} and print it.
Starter code
package main
import (
"encoding/json"
"fmt"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"encoding/json"
"fmt"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email,omitempty"`
Password string `json:"-"`
}
func main() {
b, err := json.Marshal(User{ID: 1, Name: "Ada", Password: "x"})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(b))
}Expected output
{"id":1,"name":"Ada"}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 If an <code>int</code> field tagged <code>`json:"adet,omitempty"`</code> is 0, what happens?
- "adet":null is written
- Marshal returns an error
- The field isn't written to the JSON at all Correct answer
- "adet":0 is written
Explanation: omitempty drops zero values (0, "", false, nil, empty slice/map); use it carefully where 0 is meaningful, or prefer *int.
2 Hidden field
type Hesap struct {
Ad string `json:"ad"`
Token string `json:"____"`
}
type Hesap struct {
Ad string `json:"ad"`
Token string `json:"-"`
}
Explanation: json:"-" always excludes the field from encoding and decoding.
3 Tag and effect
| Term | Meaning |
|---|---|
json:"id" |
Renames the field |
json:",omitempty" |
Skips if zero |
json:"-" |
Always skips |
json:",string" |
Writes a number as a string |