I am creating a API in golang which will simply display all data from a map in json format. endpoint: /keys
type UserController struct{}
// NewUserController function
func NewUserController() *UserController {
return &UserController{}
}
// Data struct
type Data struct {
Datakey int `json:"key"`
Datavalue string `json:"value"`
}
var datamap = make(map[int]string)
func (uc UserController) getallkeys(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
type Users []Data
var uj Users
for k, v := range datamap {
uj = Users{
Data{
Datakey: k,
Datavalue: v,
},
}
}
result, _ := json.Marshal(uj)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
fmt.Fprintf(w, "%s", result)
}
For eg: The response should be something like
[
{
"key":somekey,
"value":"somevalue"
},
{
"key":somekey,
"value":"somevalue"
}
]
I am not clear how to implement this. The above code is displaying just the last data from the map. This is incorrect but I am not sure how to proceed. It would be great if someone could help me with this.
Thanks.
At least two different problems.
First, a JSON Map cannot have an `int' key. That is part of the JSON spec. Either change it to a string or you will have to implement the MarshalJSON and UnmarshalJSON interfaces for the map, ie, for the type
type MyMap map[int]string
Google golang UnmarshalJSON time.Duration
for a number of basic examples. Also, against map and your specific key type.
Second, for a slice type
type Users []Data
adding elements requires append
uj := make(Users,0)
for k, v := range datamap {
d := Data{k,v}
uj = append(uj, d)
}
Of course, marshaling a slice produces a keyless JSON map -- likely not what you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.