Home > Backend Development > Golang > How to Parse a Nested JSON HTTP Response in Go?

How to Parse a Nested JSON HTTP Response in Go?

Patricia Arquette
Release: 2024-11-29 18:36:18
Original
642 people have browsed it

How to Parse a Nested JSON HTTP Response in Go?

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)
        }
    }

}
Copy after login

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!

source:php.cn
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