Home >Backend Development >Golang >How to Extract an IP Address from a JSON HTTP Response in Golang?
Parse JSON HTTP Response Using Golang
Parsing JSON HTTP responses in Go allows developers to extract and process data efficiently. This question addresses a scenario where a user seeks to extract the IP address from a JSON response.
The provided Go code attempts to parse the JSON using the json.Unmarshal function. However, it assigns the decoded data to a struct svc that does not accurately reflect the JSON structure.
To correctly parse the JSON, you should define structs that mirror the JSON structure, as demonstrated in the following code:
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"` }
Once you have defined the structs, you can use json.NewDecoder to decode the JSON response into an instance of the Example struct:
r := bytes.NewReader(m) decoder := json.NewDecoder(r) val := &Example{} err := decoder.Decode(val)
Using this approach, you can access the IP address by looping through the Subsets and Addresses slices within the parsed Example struct:
for _, s := range val.Subsets { for _, a := range s.Addresses { fmt.Println(a.IP) } }
The above is the detailed content of How to Extract an IP Address from a JSON HTTP Response in Golang?. For more information, please follow other related articles on the PHP Chinese website!