'Golang json collapse array of an object
In golang how can I collapse an array of an object when returning to json?
I'm not sure how to properly describe this problem but here is what I'm looking for.
{
"error_code": 422,
"errors": [
"email": [
"email is required"
]
]
}
Here's my code so far
type Error struct {
Email []string `json:"email"`
}
type Response struct {
ErrorCode int `json:"error_code"`
Errors []Error `json:"errors"`
}
func handler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(422)
json.NewEncoder(w).Encode(Response{
ErrorCode: 422,
Errors: []Error{
Error{Email: []string{"email is required"}},
},
})
}
and the result is
{
"error_code": 422,
"errors": [
{
"email": [
"email is required"
]
}
]
}
Notice how errors is an array of object, how can I avoid that and directly have "email" array under "errors"?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
