go - Parse JSON HTTP response using golang -


i trying value of "ip" following curl output:

{     "type":"example",   "data":{       "name":"abc",     "labels":{         "key":"value"     }   },   "subsets":[       {         "addresses":[           {             "ip":"192.168.103.178"         }       ],       "ports":[           {             "port":80         }       ]     }   ] } 

i have found many examples in internet parse json output of curl requests , have written following code, doesn't seem return me value of "ip"

package main  import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "time" )  type svc struct {     ip string `json:"ip"` }  func main() {  url := "http://myurl.com"  testclient := http.client{     timeout: time.second * 2, // maximum of 2 secs }  req, err := http.newrequest(http.methodget, url, nil) if err != nil {     log.fatal(err) }   res, geterr := testclient.do(req) if geterr != nil {     log.fatal(geterr) }  body, readerr := ioutil.readall(res.body) if readerr != nil {     log.fatal(readerr) }  svc1 := svc{} jsonerr := json.unmarshal(body, &svc1) if jsonerr != nil {     log.fatal(jsonerr) }  fmt.println(svc1.ip) } 

i appreciate if provide me hints on need add code value of "ip".

you can create structs mimic json structure , decode json.

package main  import (     "bytes"     "encoding/json"     "fmt"     "log" )  type example struct {     type    string   `json:"type,omitempty"`     subsets []subset `json:"subsets,omitempty"` }  type subset struct {     addresses []address `json:"addresses,omitempty"` }  type address struct {     ip string `json:"ip,omitempty"` }      func main() {      m := []byte(`{"type":"example","data": {"name": "abc","labels": {"key": "value"}},"subsets": [{"addresses": [{"ip": "192.168.103.178"}],"ports": [{"port": 80}]}]}`)      r := bytes.newreader(m)     decoder := json.newdecoder(r)      val := &example{}     err := decoder.decode(val)      if err != nil {         log.fatal(err)     }      // if want read response body     // decoder := json.newdecoder(res.body)     // err := decoder.decode(val)      // subsets slice must loop on     _, s := range val.subsets {         // within subsets, address slice         // can access each ip type address         _, := range s.addresses {             fmt.println(a.ip)         }     }  } 

the output be: 192.168.103.178

by decoding struct, can loop on slice , not limit 1 ip

example here:

https://play.golang.org/p/swa9qbwlja


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -