Parse JSON HTTP Response Using Golang: Retrieving the Value of "ip"
In this article, we will address an issue related to parsing JSON HTTP responses in Golang and specifically, how to retrieve the value of "ip" from a sample JSON output similar to the one provided in the question.
The goal is to create a program that can extract the IP address from the JSON response and print it on the console. To achieve this, we will utilize Golang's built-in JSON parsing functionality.
Let's begin by defining a custom struct named Example that reflects the structure of the JSON response. This struct will have fields for "type," "data," and "subsets." Similarly, we will define nested structs for Subset and Address to encompass the respective portions of the JSON response.
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"` }
In the main() function, we will read the JSON response from the HTTP request and decode it into the Example struct. This will involve using the json.Decoder type to parse the byte stream of the response body.
m := []byte(`{...}`) // Sample JSON response from HTTP request body r := bytes.NewReader(m) decoder := json.NewDecoder(r) val := &Example{} err := decoder.Decode(val) if err != nil { log.Fatal(err) }
Once the JSON response is decoded into the Example struct, we can access the "ip" value by iterating through the Subsets and Addresses slices.
for _, s := range val.Subsets { for _, a := range s.Addresses { fmt.Println(a.IP) } }
The output of this program will be the desired "ip" value, which in this example, is "192.168.103.178."
By using this approach, we can parse JSON HTTP responses and retrieve specific values, such as "ip," in a clean and efficient manner using Golang's JSON parsing capabilities.
The above is the detailed content of How to Extract the \'ip\' Value from a JSON HTTP Response in Golang?. For more information, please follow other related articles on the PHP Chinese website!