Ask Your Question
0

How can struct be utilized in the Go language to parse nested JSON?

asked 2021-09-19 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-05-13 01:00:00 +0000

plato gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-09-19 11:00:00 +0000

Seen: 9 times

Last updated: May 13 '21