When working with JSON responses in Go, accessing elements within nested arrays can pose challenges. Oftentimes, errors arise like "type interface {} does not support indexing" when attempting to retrieve specific data points.
To resolve this, it's crucial to understand the underlying nature of JSON responses in Go. By default, arrays are represented as []interface{} slices, while dictionaries are cast as map[string]interface{} maps. Consequently, interface variables lack support for indexing.
To access nested elements, type assertions become necessary. One approach is to do the following without error checking:
objects := result["objects"].([]interface{})
first := objects[0].(map[string]interface{})
fmt.Println(first["ITEM_ID"])
However, this method can lead to panics if the types don't align. A more robust approach is to use the two-return form and handle potential errors:
objects, ok := result["objects"].([]interface{})
if !ok {
// Handle error
}
If your JSON follows a consistent structure, consider decoding directly into a custom type:
type Result struct {
Query string `json:"query"`
Count int `json:"count"`
Objects []struct {
ItemId string `json:"ITEM_ID"`
ProdClassId string `json:"PROD_CLASS_ID"`
Available int `json:"AVAILABLE"`
} `json:"objects"`
}
Once decoded, you can seamlessly access nested elements like result.Objects[0].ItemId.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3