Senior
How can you ignore a field during JSON serialization?
sobes.tech AI
Answer from AI
In Go, to ignore a field during JSON serialization, you can use the json:"-" tag in the struct definition. This indicates to the encoding/json package not to include this field in the output JSON.
Example:
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Token string `json:"-"` // this field will not be serialized
}
user := User{ID: 1, Name: "Alice", Token: "secret"}
data, _ := json.Marshal(user)
fmt.Println(string(data)) // Outputs: {"id":1,"name":"Alice"}
Thus, the Token field will be ignored during serialization.