Having trouble decoding JSON URL GET request with golang appengine.
I'm new to golang and this is probably a simple fix.
Can't convert bytes.Buffer to struct. Am I doing it right?
Alternatively I could just query the string for the fields I want but I think that would be doing it wrong.
import {
"etc..."
}
.
.
// construct req.URL.String()
.
.
type Result struct {
Type string `json:"type"`
}
func home(w http.ResponseWriter, r *http.Request) {
.
.
.
ctx := appengine.NewContext(r)
client := urlfetch.Client(ctx)
resp, err := client.Get(req.URL.String())
buf := new(bytes.Buffer)
buf.ReadFrom(resp.Body)
fmt.Fprintln(w, buf) // successfully prints the buffer to w and confirms successful JSON request from remote server
var MyResult []Result
json.Unmarshal(buf.Bytes(), &MyResult)
for l := range MyResult {
fmt.Fprintln(w, MyResult[l].Type)
}
// Result: Empty...
// if I hard code the expected JSON string to a []byte array and Unmarshal I get a valid result from MyResult struct
I assume your json has as the most outer element an object, so it looks probably like {"key": [{"type": "foo"}]}
.
But you try to unmarshal into an array so it's expected to look like [{"type": "foo"}]
.
To be sure you would have to post an example of your json.
Thanks for the help, following the advice from this answer (link below) I was able to figure out the correct json structure and I was missing a tier in the struct declaration.
Golang issue with accessing Nested JSON Array after Unmarshalling
// fixed
type Result struct {
Features []struct {
Type string `json:"type"`
.
.
.