4

Is there any library/package that returns the json string received in response to an http request. It's pretty straightforward, so I can write my own, but would prefer existing/tested code over reinventing the wheel.

Currently, I have:

func getJsonStr(url string) ([]byte, error) {   
    resp, err := http.Get(url)
    if err != nil {
        return []byte{0}, err
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return []byte{0}, err
    }
    return body, nil
}

EDIT: I'm looking for something like Node's 'request' module, which lets me do it in one line, like so: jsonStr, err := getJsonStr(url).

1
  • BTW, use return nil, err instead of what you have which is allocating a one element slice no one should be looking at anyway (if you really want an non-nil but empty slice it would be []byte{}). If you want a one liner, then just write the above function somewhere once and use the exact one line you give wherever you need it.
    – Dave C
    Commented Apr 11, 2015 at 22:26

2 Answers 2

10

Since you didn't want to define a struct, it's also possible (but a bit ugly) to unmarshal into a map of type map[string]interface{}{}

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {

    data := map[string]interface{}{}

    r, _ := http.Get("http://api.stackoverflow.com/1.1/tags?pagesize=100&page=1")
    defer r.Body.Close()

    body, _ := ioutil.ReadAll(r.Body)
    json.Unmarshal(body, &data)

    fmt.Println("Total:", data["total"], "page:", data["page"], "pagesize:", data["pagesize"])
    // Total: 34055 page: 1 pagesize: 100
}
7

There is nothing wrong it using existing system package and it fairly simple to retrieve json data over http in go

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

func main() {
    var data struct {
        Items []struct {
            Name              string
            Count             int
            Is_required       bool
            Is_moderator_only bool
            Has_synonyms      bool
        }
    }

    r, _ := http.Get("https://api.stackexchange.com/2.2/tags?page=1&pagesize=100&order=desc&sort=popular&site=stackoverflow")
    defer r.Body.Close()

    dec := json.NewDecoder(r.Body)
    dec.Decode(&data)

    for _, item := range data.Items {
        fmt.Printf("%s = %d\n", item.Name, item.Count)
    }

}

Output go run main.go

java = 781454
javascript = 769128
c# = 744294
php = 692360
android = 617892
jquery = 570461
python = 379608
html = 374617
c++ = 341533
ios = 300992
mysql = 296223
css = 276063
sql = 258178
asp.net = 244833
objective-c = 215095
.net = 202087
iphone = 199749
ruby-on-rails = 190497
c = 166226
ruby = 123840
sql-server = 119341
arrays = 116975
ajax = 109786
regex = 107215
xml = 106705
asp.net-mvc = 101921
json = 101545
wpf = 96016
linux = 92266
django = 88008
database = 86638
eclipse = 79952
vb.net = 78888
r = 78401
xcode = 76326
windows = 74359
angularjs = 73266
string = 71149
html5 = 68094
node.js = 66731
wordpress = 65125
multithreading = 64168
facebook = 62460
excel = 58402
spring = 57380
image = 56798
winforms = 55268
forms = 54263
ruby-on-rails-3 = 52611
osx = 51292
oracle = 50876
git = 50019
performance = 48867
swing = 48768
algorithm = 48258
apache = 47355
bash = 46347
linq = 45169
visual-studio-2010 = 43907
entity-framework = 43776
perl = 42740
web-services = 42609
matlab = 42112
hibernate = 41410
visual-studio = 40307
wcf = 39948
sql-server-2008 = 39394
mongodb = 38632
asp.net-mvc-3 = 38018
list = 37914
qt = 37505
.htaccess = 37305
css3 = 36505
vba = 36368
sqlite = 36274
actionscript-3 = 35594
file = 35171
twitter-bootstrap = 34911
postgresql = 34757
function = 34747
codeigniter = 33439
api = 32964
class = 32888
scala = 32763
shell = 32407
google-maps = 31961
cocoa = 31744
ipad = 31600
jsp = 31510
cocoa-touch = 30994
tsql = 30976
sockets = 30635
flash = 30555
jquery-ui = 30506
asp.net-mvc-4 = 30278
validation = 30166
security = 30035
delphi = 29758
unit-testing = 29717
rest = 29475
3
  • Yep, I could do that, but 2 things: 1. I don't want to type out all that every time I want to get a json. I want a one-liner like: jsonStr, err := jsonStr.get(url). 2. I don't want to have to define a struct for every time I get a json. I'm getting it from different sources, and it's easier to just get a string and put it in jsbeautifier.
    – tldr
    Commented Aug 1, 2013 at 17:44
  • You can use github.com/bitly/go-simplejson fairly simple to use
    – Baba
    Commented Aug 2, 2013 at 12:54
  • 2
    Or just write a function that takes in a URL to do all that, extremely simple.
    – Stasis
    Commented Feb 14, 2014 at 19:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.