【问题标题】:JSON Response: return nested JSONJSON 响应:返回嵌套的 JSON
【发布时间】:2020-10-23 01:02:42
【问题描述】:

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

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

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

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

data["result"] = resp

示例响应应如下所示:

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

响应可以是一个对象或对象列表。 这是 Python 格式的,我如何在 Go 中做到这一点?

【问题讨论】:

  • (Python 术语中的字典)。我认为应该是map 而不是struct
  • 我不确定在这里使用哪一个,map 或 struct。实际的 resp 包含我使用 Gorm 从 db 表中获取的数据。你能举个例子吗?我仅在 4-5 天前才开始使用 Go。

标签: json go go-gin


【解决方案1】:

你可以在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",
    })

【讨论】:

    猜你喜欢
    • 2017-03-15
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 2020-01-13
    相关资源
    最近更新 更多