Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go JSON with simplejson

Tags:

json

go

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

like image 302
user914584 Avatar asked Jul 12 '26 12:07

user914584


1 Answers

You have a few mistakes:

  1. 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.
  2. 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)
}
like image 102
Kavu Avatar answered Jul 14 '26 09:07

Kavu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!