You have a few errors:
- If you check the JSON response, you will notice that the field is
totalnot a string, so when accessing the field, you should use the method MustInt(), not String(). Printf()the method call was completely wrong. You must pass the "pattern" and then pass the arguments corresponding to the number of "placeholders".
By the way, I highly recommend that you check err != nileverywhere, which will help you a lot.
Here is a working example:
package main
import (
"fmt"
"github.com/bitly/go-simplejson"
"io/ioutil"
"log"
"net/http"
)
func main() {
url := "http://api.stackoverflow.com/1.1/tags?pagesize=100&page=1"
res, err := http.Get(url)
if err != nil {
log.Fatalln(err)
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatalln(err)
}
js, err := simplejson.NewJson(body)
if err != nil {
log.Fatalln(err)
}
total := js.Get("total").MustInt()
if err != nil {
log.Fatalln(err)
}
fmt.Printf("Total:%s", total)
}
source
share