I am building a REST api in GO and I am able to fetch the JSON response from the server. I am looking forward to store the JSON response in sort of a container (array) and return that structure from the function. I have my data structures defined something like this - {
type Payload struct {
Stuff []Data `json:"data"` // holds the JSON response returned
}
type Container struct {
container []Payload
}
type ListContainersResponse struct {
Data []Container // want this thing to be returned from the function
}
func (client *Client) ListContainers() (ListContainersResponse, error) {
// fetches the JSON response
var p Payload
// XYZ is something of the type ListContainersResponse which needs to be returned
return XYZ
}
}
iterating over p gives me my JSON structure and I want to append it to a Data[] container which can hold this returned JSON response and returned back from the function. I tried playing around with it but get some exceptions. Could someone help me with this?
Thanks, I got my code working by doing something like this {
var result ListContainersResponse
var temp Container
temp.container = append(temp.container, p)
result.Data = append(result.Data, temp)
}
Assuming you've already got the JSON decoded into an instance of Payload p.
func (client *Client) ListContainers() (ListContainersResponse, error) {
// fetches the JSON response
var p Payload
XYZ := ListContainersResponse {
Data: []Container {
container: []Payload {
{p},
},
},
}
// XYZ is something of the type ListContainersResponse which needs to be returned
return XYZ
}
Additionally, in case any else is interested, here is how I would get the JSON into the struct:
var p Payload
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&p)
Where r
is of type http.Request
. I expect the json string looks something like:
{
"data": [...]
}