I'm attempting to use the USDA's Farmers Market Directory API to receive a data about where nearby farmer's markets are located, using a zip code. I store the unmarshalled body of the response in:
type marketResponse struct {
MapsLink string `json:"GoogleLink"`
Address string `json:"Address"`
Schedule string `json:"Schedule"`
Products string `json:"Products"`
}
Using the code:
//TODO: location: "http://search.ams.usda.gov/farmersmarkets/v1/data.svc/locSearch?lat=" + lat + "&lng=" + lng
resp, err := http.Get("http://search.ams.usda.gov/farmersmarkets/v1/data.svc/zipSearch?zip=" + zipcode)
if err != nil {
log.Printf("Could net search zipcode %s: %v", zipcode, err)
}
defer func() {
if err := resp.Body.Close(); err != nil {
log.Println(err)
}
}()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println(err)
}
newMarket := &marketResponse{}
if err := json.Unmarshal(body, newMarket); err != nil {
log.Println(err)
}
log.Println("response: " + newMarket.Address)
The problem is, the response body is in JSONp, and I'm unmarshalling in JSON. How can I unmarshal in JSONp, using an external package, or not?
The response body is JSON - as per the response's Content-Type:application/json; charset=utf-8
header.
The issue is that your marketResponse
struct bears no relation to the JSON returned. Using JSON-to-Go, your struct should look like:
type MarketResponse struct {
Results []Result `json:"results"`
}
type Result struct {
ID string `json:"id"`
Marketname string `json:"marketname"`
}
It's not clear where your existing marketResponse
struct fits here, as neither API endpoint returns data with that structure.
PS: You should handle (or return) your errors and not just log them; logging them still means that your function continues with unhandled error. Your code might then panic when it encounters a nil response body or JSON unmarshalling error.