我正在使用一些数据公开 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"`
}
}
Run Code Online (Sandbox Code Playgroud)
我使用 json 标签来表示调用端点时结构字段的外观。使用上述内容,我得到以下有效负载作为响应:
{
"Config": {
"allow": false,
"expired": false,
},
"Database": {
"healthy": true,
"wait_count": 1,
},
}
Run Code Online (Sandbox Code Playgroud)
我希望 forConfig和Database为小写,意思是config和database。但是,将它们更改为 Go 代码中的值意味着"encoding/json"包无法“看到”它们,因为它们没有导出到包范围之外。
如何将 json 响应负载中的嵌套结构小写?
小智 6
嵌套结构是包含结构中的一个字段。像处理其他字段一样添加字段标签:
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
}
Run Code Online (Sandbox Code Playgroud)