How to hide struct fields when serializing to JSON in Go?
Hello everyone! I just started learning Go and encountered a problem when working with JSON. I have a `User` struct that contains many fields, but in the API JSON response I need to return only some of them. For example, I don't want to show the password and the internal user ID.
Here's my code:
```go
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"password"`
InternalID string `json:"internal_id"`
}
func main() {
user := User{
ID: 1,
Name: "Ivan",
Email: "ivan@example.com",
Password: "secret123",
InternalID: "int-001",
}
jsonData, _ := json.Marshal(user)
fmt.Println(string(jsonData))
// Outputs: {"id":1,"name":"Iva
No answers yet.
Log in to leave an answer