I have code where I am pulling out data from mongo & would like to give it out as an API response. My main challenge is not being able to transform data before pushing it out.
var result interface{}
respBody, err := json.Marshal(result)
Is it possible to edit marshalled result before it goes out? eg. Take out some fields?
A common way to accomplish what you described you're trying would be something like this:
type Data struct {
Name string
Age int
Address *Address
// more fields of your data object
}
type Response struct {
Name string `json:"name"`
Age int `json:"age"`
}
func GetResponse(d Data) ([]byte, error) {
r := Response{
Name: d.Name,
Age: d.Age,
// anything else
}
return json.Marshal(r)
}
If you just want to remove some fields from json response, then you can do as below:
package main
import (
"fmt"
"encoding/json"
)
type User struct {
Name string `json:"name"`
Password string `json:"-"` . //remove from json
}
func main() {
fmt.Println("Hello, playground")
u := &User{Name:"alpha", Password: "beta"}
b, _ := json.Marshal(u)
fmt.Println(string(b))
}
For some use cases, you can also have custom json Marshaller by implementing the MarshalJSON
on User struct.
For example to change field names:
func (u *User) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
Name string `json:"name"`
Key string `json:"key"`
}{
Name: u.Name,
Key: u.Password,
})
}