Home > Backend Development > Golang > How to Extract an IP Address from a JSON HTTP Response in Golang?

How to Extract an IP Address from a JSON HTTP Response in Golang?

Patricia Arquette
Release: 2024-12-01 18:50:10
Original
859 people have browsed it

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"`
}
Copy after login

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)
Copy after login

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)
    }
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template