In Golang, how to embed returning value of method call into JSON output?

Seeking for a clean approach to embed returning value of method call into JSON output. It would be great if I don’t need to write custom JSON marshaler.

For example, if User struct has FirstName and LastName fields and FullName() method, how could I concatenate fields and embed full_name into JSON output?

 type User struct {
     FirstName string `json:"first_name"`
     LastName  string `json:"last_name"`
 }

 func (u User) FullName() string {
     return fmt.Sprintf("%s %s", u.FirstName, u.LastName)
 }

Expected JSON:

 {
     "first_name": "John",
     "last_name":  "Smith",
     "full_name":  "John Smith"
 }


Source: json

Leave a Reply