英文:
How do I lowercase a nested struct name when using json.marshal?
问题
我正在暴露一个带有一些数据的 REST 端点。它是一个结构体,比如说:
type status struct {
Config struct {
Allow bool `json:"allow"`
Expired bool `json:"expired"`
}
Database struct {
Healthy bool `json:"healthy"`
WaitCount int64 `json:"wait_count"`
}
}
我使用 json
标签来表示在调用端点时结构字段应该如何显示。使用上述代码,我得到以下响应负载:
{
"Config": {
"allow": false,
"expired": false
},
"Database": {
"healthy": true,
"wait_count": 1
}
}
我希望 Config
和 Database
的首字母小写,即 config
和 database
。然而,在 Go 代码中将它们更改为小写意味着 encoding/json
包无法“看到”它们,因为它们没有在包范围之外导出。
如何将嵌套结构体在 JSON 响应负载中转换为小写?
英文:
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?
答案1
得分: 6
嵌套结构是包含结构中的一个字段。像其他字段一样,为嵌套结构添加字段标签:
type status struct {
Config struct {
Allow bool `json:"allow"`
Expired bool `json:"expired"`
} `json:"config"` // <-- 在这里添加标签 ...
Database struct {
Healthy bool `json:"healthy"`
WaitCount int64 `json:"wait_count"`
} `json:"database"` // <-- ... 和这里
}
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论