drsfgwuw61488 2016-04-24 00:57
浏览 8
已采纳

如何解组请求中返回的JSON?

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?

  • 写回答

1条回答 默认 最新

  • doujumiao5024 2016-04-24 01:17
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算