Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Structs can be utilized in Go language to parse nested JSON data by defining a struct that matches the structure of the JSON data. Here is an example:

Let's assume we have the following JSON data:

{
    "name": "John",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "New York",
        "state": "NY"
    }
}

We can create a struct that matches the structure of this JSON data:

type Person struct {
    Name    string    `json:"name"`
    Age     int       `json:"age"`
    Address struct {
        Street string `json:"street"`
        City   string `json:"city"`
        State  string `json:"state"`
    } `json:"address"`
}

In this struct, we have defined a field for each key in the JSON data. For the "address" field, we have defined another nested struct that matches the structure of the nested JSON data.

We can then use the json.Unmarshal() function to parse the JSON data into an instance of this struct:

jsonData := `
{
    "name": "John",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "New York",
        "state": "NY"
    }
}
`

var person Person
if err := json.Unmarshal([]byte(jsonData), &person); err != nil {
    log.Fatal(err)
}

fmt.Println(person.Name)       // Output: John
fmt.Println(person.Address.City)   // Output: New York

After parsing the JSON data, we can access the fields of the struct to retrieve the values of the corresponding data in the JSON data. We can use dot notation to access the fields of a nested struct.