3

I am trying to return a JSON response something like this:

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

where resp contains data from a db table (struct) which I have converted to JSON.

I need to return the response in data key in this format:

data["result"] = resp

Sample response should look like:

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

The response can either be an object or a list of objects. This is in Python format, how do I do this in Go?

David Buck
  • 3,752
  • 35
  • 31
  • 35
Ankita Gupta
  • 155
  • 2
  • 14
  • *(dictionary in Python's term)*.I think it should be a `map` instead of a `struct`. – jizhihaoSAMA Jul 02 '20 at 12:52
  • I am not sure which one to use here, map or struct. The actual resp contains data that I fetched from a db table using Gorm. Could you please provide an example? I have started working with Go 4-5 days ago only. – Ankita Gupta Jul 02 '20 at 12:58

1 Answers1

7

You could see it in the source of gin:

type H map[string]interface{}

So you could use(nested gin.H):

c.JSON(http.StatusOK, gin.H{"data": 
        gin.H{
            "result": []string{"This is a sample response"},
        },
        "code": http.StatusOK, 
        "status": "success",
    })
jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49
  • 1
    Thank you sir, using nested gin.H solved my problem easily, I was worried that I have to use a strong type for every return, ughh.. – Shino Lex Nov 01 '22 at 12:39
  • @ShinoLex That is the common problem in static language like go. So when you try to read from `interface{}` you may need to use type assertion. – jizhihaoSAMA Nov 02 '22 at 06:21