Skip to content

Instantly share code, notes, and snippets.

@gnilchee
Last active January 9, 2017 06:23
Show Gist options
  • Save gnilchee/09fc88e45888f92df33d16866e0f08a6 to your computer and use it in GitHub Desktop.
Save gnilchee/09fc88e45888f92df33d16866e0f08a6 to your computer and use it in GitHub Desktop.
Using net/http and json encoding to pull out nested json values and stored into map
package main
import (
"fmt"
"log"
"net/http"
"io/ioutil"
"encoding/json"
)
/*
{
"resources": {
"core": {
"limit": 60,
"remaining": 60,
"reset": 1483945005
},
"search": {
"limit": 10,
"remaining": 10,
"reset": 1483941465
}
},
"rate": {
"limit": 60,
"remaining": 60,
"reset": 1483945005
}
}
*/
func main() {
// Simple Get request to the rate_limit api
res, err := http.Get("https://api.github.com/rate_limit")
if err != nil {
log.Fatal(err)
}
// Storing response into variable github
github, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Fatal(err)
}
// Building variable map to capture response into
var data map[string]interface{}
// Unmarshaling github into data variable
err = json.Unmarshal(github, &data)
if err != nil {
log.Fatal(err)
}
// Decending into nested "rate" json to call k,v pairs
rate, ok := data["rate"].(map[string]interface{})
if !ok {
log.Fatal("oh no!")
}
// Call specific value and print
fmt.Println("Rate Limit:", rate["limit"])
// Iterate through k, v pair in rate map
for k, v := range rate {
fmt.Printf("Key: %v, Value: %v\n", k, v)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment