duanrong5927 2013-11-29 22:07
浏览 38
已采纳

golang GET请求json类型在运行时错误

im trying to write a small app using usa today's RESTful api in golang, but it seems i have an error in type conversion when trying to parse the GET request from the api. My program compiles which makes me think the types are right, but at run time my program crashes

i got a good idea how to map incoming json in which you don't have premade structures for using the type interface {} from http://blog.golang.org/json-and-go

here's what my golang code looks like:

// get request to API
resp, err := http.Get("http://api.usatoday.com/open/articles/topnews/home?count=10&days=0&page=0&encoding=json&api_key=myApiKey")

if(err == nil){
    body, err := ioutil.ReadAll(resp.Body)
    if(err == nil) {
        var data interface{}
        json.Unmarshal(body, &data)

        var m = data.(map[string] []interface{})            
        var articles = m["stories"]
        var newArticle interface {}

        for newArticle = range articles {
            var n = newArticle.(map[string] string)

            fmt.Printf("<h2>Title: " + n["title"] + "</h2>")
            fmt.Printf("<p>description: " + n["description"] + "</p>")
            fmt.Printf("<p>link to article: " + n["link"] + "</p>")
        }

    } else {
        fmt.Println(err)
    }

} else {
    fmt.Println(err)
}

and here's a small example of the get request response looks like

{
    "stories": [{
        "description": "Despite the fact that shoppers descended upon stores after giving thanks, Black Friday wasn't without its share of brawls.",
        "guid": [{
            "isPermalink": "true",
            "value": "http:\/\/apidata.usatoday.com\/story\/news\/nation-now\/2013\/11\/29\/black-friday-police-violence\/3783467\/?kjnd=Pvzhnh75%2BZ3dnzxHVv571HQOfzKReZECsSPCBGnAiXlbHijpqdc3TQoe4dYfzVlB-8d81f9e3-0b56-421e-a5da-121f9eb83de3_E50GPTZL1%2FYloJsxpxSnp8AhoO2O9prQtDTYiwN3sbV0SfQ5wriH1zooo6XgNPTr"
        }],
        "link": "http:\/\/apidata.usatoday.com\/story\/news\/nation-now\/2013\/11\/29\/black-friday-police-violence\/3783467\/?kjnd=LOCSg6KVoQR3pwnZyGmcgcDZXwce0MwglPkURuQ%2BzMkUdNzQ2GXJr%2FPfLCl4Hf38-8d81f9e3-0b56-421e-a5da-121f9eb83de3_Zp5d44u%2F3U2IkXWRbNP0OwyXjRkEgShxoJC0wp7%2FOJoFPCI979Zw4qgNkWkOG1x1",
        "pubDate": "Fri, 29 Nov 2013 02:57:43 GMT",
        "title": "Black Friday frenzy leads to reports of violence"
    }, {
        "description": "President Obama's law faces hurdles beyond the Supreme Court case on the birth control mandate.",
        "guid": [{
            "isPermalink": "true",
            "value": "http:\/\/apidata.usatoday.com\/story\/news\/politics\/2013\/11\/29\/supreme-court-obamacare-lawsuits-irs\/3760811\/?kjnd=sCqadf244XkWTNcS0zAI%2Ba25XsnxwAX3ahu8NP0bzKdU4Kx31rJsa0cWlhvnwMl8-8d81f9e3-0b56-421e-a5da-121f9eb83de3_wtrtyHNPao7CqrB0IR7%2Bj3GFwJMhSYFSrOrrGZCkX2BStipIyyDtQoTLLFCGoLj0"
        }],
        "link": "http:\/\/apidata.usatoday.com\/story\/news\/politics\/2013\/11\/29\/supreme-court-obamacare-lawsuits-irs\/3760811\/?kjnd=Be2GdDxc2cZdIOPiCpcL9vz%2FFvmT859xSGoVutxwurqJ%2FCwvTt8vjs2s9MHzI1hO-8d81f9e3-0b56-421e-a5da-121f9eb83de3_88mb%2BwbADj1MvtG9%2BiYMhVS43CRGBEVdn0v5QJsORviARUA3qR0iE9LBr7NpNrT7",
        "pubDate": "Fri, 29 Nov 2013 11:12:08 GMT",
        "title": "Long-shot legal challenges to health care law abound"
    }
    }]
}

AND finally here's what the error looks like at runtime

panic: interface conversion: interface is map[string]interface {}, not map[string][]interface {}

not really sure how i should go about this, so anyone with pre-existing knowledge of working with RESTful api's in golang that would have some insight would be greatly appreciated!

  • 写回答

3条回答 默认 最新

  • duanlei1957 2013-11-29 23:58
    关注

    i ended up fixing it using some structures that matched the json objects... which was kind of a pain.

    here it is if anyone ever wants to use this api in golang

    type stories struct {
        Stories []story
    }
    type story struct {
        Description string
        Guid []guid
        Link string
        PubDate string
        Title string
    }
    type guid struct {
        IsPermalink string
        Value string
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。