Home >Backend Development >Golang >How Can I Extract the \'ip\' Value from a JSON HTTP Response in Golang?

How Can I Extract the \'ip\' Value from a JSON HTTP Response in Golang?

Susan Sarandon
Susan SarandonOriginal
2024-12-09 02:36:10911browse

How Can I Extract the

Parse JSON HTTP Response Using Golang

To retrieve the value of "ip" from the provided JSON response, it is recommended to utilize custom structs that mirror the JSON structure and decode the response accordingly. Consider the following code:

import (
    "bytes"
    "encoding/json"
    "fmt"
    "log"
)

// Define structs to match the JSON structure
type Example struct {
    Type    string   `json:"type"`
    Subsets []Subset `json:"subsets"`
}

type Subset struct {
    Addresses []Address `json:"addresses"`
}

type Address struct {
    IP string `json:"ip"`
}

func main() {
    // Define the JSON input
    m := []byte(`{"type":"example","data":{"name":"abc","labels":{"key":"value"}},"subsets":[{"addresses":[{"ip":"192.168.103.178"}],"ports":[{"port":80}]}]}`)

    // Create a reader from the JSON input
    r := bytes.NewReader(m)
    decoder := json.NewDecoder(r)

    // Decode the JSON into the Example struct
    val := &Example{}
    if err := decoder.Decode(val); err != nil {
        log.Fatal(err)
    }

    // Iterate over the Subsets and Addresses slices to access each IP
    for _, s := range val.Subsets {
        for _, a := range s.Addresses {
            fmt.Println(a.IP)
        }
    }
}

This approach allows for decoding the JSON response into custom structs, providing the ability to loop over slices and retrieve specific values by accessing struct members (e.g., a.IP). The provided code demonstrates the end-to-end workflow of reading a JSON response, decoding it into structs, and extracting specific values.

The above is the detailed content of How Can I Extract the \'ip\' Value from a JSON HTTP Response in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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