JSON 响应 : return nested JSON

标签 json go go-gin

我正在尝试返回类似这样的 JSON 响应:

c.JSON(http.StatusOK, gin.H{"data": resp, "code": http.StatusOK, "status": "success"})

其中 resp 包含我已转换为 JSON 的数据库表(结构)中的数据。

我需要以这种格式返回数据键中的响应:

data["result"] = resp

示例响应应如下所示:

{
"data": {"result" : ["This is a sample response"]}
}

响应可以是对象或对象列表。 这是 Python 格式,我如何在 Go 中执行此操作?

最佳答案

你可以在 gin 的源代码中看到它:

type H map[string]interface{}

所以你可以使用(嵌套的 gin.H):

c.JSON(http.StatusOK, gin.H{"data": 
        gin.H{
            "result": []string{"This is a sample response"},
        },
        "code": http.StatusOK, 
        "status": "success",
    })

关于JSON 响应 : return nested JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62696187/

相关文章:

python - 无法从解析的字典中返回 "valid"字段

java - 春假服务

go - 错误:在services.GetCharactersID的参数中不能使用c.Param(“id”)(类型字符串)作为int类型。

go - 高并发下Go `net/http`的一些困惑

json - Web 服务架构中 MVC 设计模式的实现是否应该由多个组件组成?

javascript - 如何使用 Vue-Loader/Webpack 路径到外部(动态) Assets

go - goroutine 调用行之后的行是否比 goroutine 的第一行更早开始?

google-app-engine - 将实体放入 Google App Engine 数据存储区时 bool 值始终为假 - Golang

xml - 在 Go 中将 Marshall 映射到 XML

go - Gin-Gonic内容类型限制