Go json with simple

Trying to use 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 to work! Trying to access shared fields and tags

+3
source share
1 answer

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)
    }

    // 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)
}
+6
source

All Articles