Golang json group by

108 views
Skip to first unread message

tien...@gmail.com

unread,
Jul 12, 2020, 2:21:43 AM7/12/20
to golang-nuts
I have function as below

I have function as below

func Get DataById(w http.ResponseWriter, r *http.Request) {
 uid := "11111"
 data := models.GetTransport(uid)

 w.WriteHeader(http.StatusOK) //200
 if data == nil {
 resp := u.Message(false, "Can not found")
 u.Respond(w, resp)
 } else {
 resp := u.Message(true, "success")
 resp["data"] = data
 u.Respond(w, resp)
 }
}


End it was response data

{
"data": [
{
"day": 1,
"begin": "AAAA",
},
{
"day": 1,
"begin": "BBBB",
},
{
"day": 2,
"begin": "CCCC",
},
{
"day": 2,
"begin": "DDDD",
},
]
}

But I want group by Day and output json as below


{
 
"data": [
  "day1:"
[
  {
  "begin": "AAAA",
 
},
 
{
 
"begin": "BBBB",
 
},
]
  "day2:"
[
{
  "begin": "CCCC",
 
},
 
{
 
"begin": "DDDD",
 
},
]
  ]
}

How can I do it, please give me advice.
Thanks a lot




Erman Imer

unread,
Jul 13, 2020, 3:21:51 AM7/13/20
to golang-nuts
Hello,

You can use a map, map[string][]Data.

Please check the sample code below:
Reply all
Reply to author
Forward
0 new messages