I have the following snippet of code from a function which returns a HTTP response:
res := make([]map[string]interface{}, 0)
for d := range Channel {
if d.Error != nil {
return d.Error
}
res = append(res, d.Data.(map[string]interface{}))
}
return c.JSON(http.StatusOK, res)
The HTTP response is basically a list of maps.
However, I want to modify this response such that I return a map of list of maps. How can I do this?
For instance, in the example below - the outer map has the key "directories" and has a list of maps as the corresponding value.
{
"directories": [
{
"name": "bin"
},
{
"name": "cfg"
}
]
}
I have been referring to the documentation but it got me more confused wrt this.
to return a map of list of map you can refer below code:
type listMapType []map[string]string
type mapType map[string]string
func main() {
map1 := make(map[string]listMapType, 0)
mapList := make(listMapType,0)
valueMap :=mapType{"1":"2"}
mapList = append(mapList,valueMap)
map1["d"] = mapList
map2, _ := json.Marshal(map1)
fmt.Println(string(map2))
}
I assume the res
object are the slice/array that will be the value of directories
item on the map. then you can do something like code below.
res := make([]map[string]interface{}, 0)
// ...
resMap := make(map[string][]map[string]interface{})
resMap["directories"] = res
return c.JSON(http.StatusOK, resMap)
Create resMap
object with type is map[string][]map[string]interface{}
, then insert new item with directories
as key and res
as the value.