Go JSON with simplejson
go, json
Solution
You have a few mistakes:
- If you'll check the JSON response you'll notice that `total` field is not string, that's why you should use `MustInt()` method, not `String()`, when you are accessing the field.
- `Printf()` method invocation was totally wrong. You should pass a "template", and then pass arguments appropriate to the number of "placeholders".
By the way, I strongly recomend you to check `err != nil` everywhere, that'll help you a lot.
Here is the 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)
}
// fmt.Printf("%s\n", string(body))
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)
}
Problem
Trying to use the JSON lib from "github.com/bitly/go-simplejson" ``` url = "http://api.stackoverflow.com/1.1/tags?pagesize=100&page=1" res, err := http.Get(url) body, err := ioutil.ReadAll(res.Body) fmt.Printf("%s\n", string(body)) //WORKS js, err := simplejson.NewJson(body) total,_ := js.Get("total").String() fmt.Printf("Total:%s"+total ) ``` But it seems it doenst work !? Trying to access the total and tag fields