I'm exposing a REST endpoint with some data. It's a struct, say:
type status struct {
Config struct {
Allow bool `json:"allow"`
Expired bool `json:"expired"`
}
Database struct {
Healthy bool `json:"healthy"`
WaitCount int64 `json:"wait_count"`
}
}
I'm using the json tag to denote how a struct field should look when calling the endpoint. Using the above, I'm getting the following payload as response:
{
"Config": {
"allow": false,
"expired": false,
},
"Database": {
"healthy": true,
"wait_count": 1,
},
}
I'd like for Config
and Database
to be lowercase, meaning config
and database
. However, changing them to that in the Go code means the "encoding/json"
package cannot "see" them as they aren't exported outside of the package scope.
How do I lowercase the nested struct's in the json response payload?
CodePudding user response:
The nested struct is a field in the containing struct. Add a field tags as you did with the other fields:
type status struct {
Config struct {
Allow bool `json:"allow"`
Expired bool `json:"expired"`
} `json:"config"` // <-- add tag here ...
Database struct {
Healthy bool `json:"healthy"`
WaitCount int64 `json:"wait_count"`
} `json:"database"` // <-- ... and here
}