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.
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
Asked: 2021-09-19 11:00:00 +0000
Seen: 9 times
Last updated: May 13 '21
How can JSON be decoded while using a universal interface as a field?
How can I convert a `dataframe` from Polars to `serde_json::Value` using serialization?
In RobotFramework, can multiple key-value pairs in JSON format be obtained and saved to a JSON file?
How can JSON objects with dynamic keys be extracted in Athena/Presto?
What is the method for parsing a single JSON object in Android?
"What is the method of utilizing CURL POST with a payload in Json format?"
How can a JSON serialize detect a potential object cycle in .NET MAUI?