Golang 变换 JSON
Golang Transform JSON
我正在研究 Golang,GORM 以使用 Echo Framework 实施 API
我正在使用以下结构和函数生成 JSON
type User struct {
gorm.Model
Name string `json:"name"`
Username string `json:"username"`
Password string
}
func GetUsers(c echo.Context) error {
db := db.GetDBInstance()
users := []model.User{}
db.Find(&users)
return c.JSON(http.StatusOK, users)
}
这是我的 JSON 回复
[
{
ID: 1,
CreatedAt: "2020-04-21T05:28:53.34966Z",
UpdatedAt: "0001-01-01T00:00:00Z",
DeletedAt: null,
name: "",
username: "test",
Password: "test123"
}
]
我想转换成下面的JSON
{
data: [{
ID: 1,
CreatedAt: "2020-04-21T05:28:53.34966Z",
UpdatedAt: "0001-01-01T00:00:00Z",
DeletedAt: null,
name: "",
username: "test",
Password: "test123"
}]
}
任何帮助将不胜感激
您可以创建一个新结构来执行此操作
type Data struct{
Data []model.User `json:"data"`
}
func GetUsers(c echo.Context) error {
db := db.GetDBInstance()
users := []model.User{}
db.Find(&users)
data := &Data{
Data: users,
}
return c.JSON(http.StatusOK, data)
}
您可以创建帮助程序来处理响应,例如:
helper/response_formatter.go
响应结构:
type Response struct {
Data interface{} `json:"data"`
}
响应格式化函数:
func ResponseFormatter(data interface{}) Response {
response := Response{
Data: data,
}
return response
}
调用函数
import helper
...
response := helper.ResponseFormatter(users)
我正在研究 Golang,GORM 以使用 Echo Framework 实施 API
我正在使用以下结构和函数生成 JSON
type User struct {
gorm.Model
Name string `json:"name"`
Username string `json:"username"`
Password string
}
func GetUsers(c echo.Context) error {
db := db.GetDBInstance()
users := []model.User{}
db.Find(&users)
return c.JSON(http.StatusOK, users)
}
这是我的 JSON 回复
[
{
ID: 1,
CreatedAt: "2020-04-21T05:28:53.34966Z",
UpdatedAt: "0001-01-01T00:00:00Z",
DeletedAt: null,
name: "",
username: "test",
Password: "test123"
}
]
我想转换成下面的JSON
{
data: [{
ID: 1,
CreatedAt: "2020-04-21T05:28:53.34966Z",
UpdatedAt: "0001-01-01T00:00:00Z",
DeletedAt: null,
name: "",
username: "test",
Password: "test123"
}]
}
任何帮助将不胜感激
您可以创建一个新结构来执行此操作
type Data struct{
Data []model.User `json:"data"`
}
func GetUsers(c echo.Context) error {
db := db.GetDBInstance()
users := []model.User{}
db.Find(&users)
data := &Data{
Data: users,
}
return c.JSON(http.StatusOK, data)
}
您可以创建帮助程序来处理响应,例如:
helper/response_formatter.go
响应结构:
type Response struct {
Data interface{} `json:"data"`
}
响应格式化函数:
func ResponseFormatter(data interface{}) Response {
response := Response{
Data: data,
}
return response
}
调用函数
import helper
...
response := helper.ResponseFormatter(users)