Parse JSON HTTP Response using Go
To parse a JSON response from an HTTP request in Golang, you can use JSON decoding to convert the response body into a struct that reflects the JSON structure.
Code Example
The following code demonstrates how to parse a JSON response with nested structs to obtain the value of "ip":
package main import ( "bytes" "encoding/json" "fmt" "log" "net/http" "time" ) 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) } // Iterate over subsets and addresses to access each IP for _, s := range val.Subsets { for _, a := range s.Addresses { fmt.Println(a.IP) } } }
By leveraging JSON decoding to create a struct that mirrors the JSON structure, you can dynamically access and parse the data within the response, including nested elements such as the "ip" field.
The above is the detailed content of How to Parse a Nested JSON HTTP Response in Go?. For more information, please follow other related articles on the PHP Chinese website!