Last Updated: February 25, 2016
·
788
· bagwanpankaj

Go an Arbitary JSON

Go is statically typed language, and one knows how difficult it is when you get arbitary json as a response. Here is how to access arbitrary JSON

lets assume that we have resp *http.Response object, here is how to access it

body, err := ioutil.ReadAll(resp.Body)
var f interface{}
err = json.Unmarshal(body, &f)
if(err != nil){
  panic(err)
}
fmt.Println(f.(map[string]interface{})["id"]);

Here we are asserting that, response is an unordered map, whose keys are strings and values can again be interface. This way we did type assertion, and can access first level keys, as done in example