Home >Backend Development >Golang >How to Handle JSON Responses with Dynamic Keys in Go?
Handling JSON Responses with Dynamic Keys in Golang
When encountering JSON responses with arbitrary keys, it can be challenging to create a corresponding struct. One such example is the provided JSON response containing nested maps with varying keys representing image sizes.
To address this issue, consider using a map-based data structure. In Golang, a map is a collection of key-value pairs where the keys are strings.
Solution:
Define a struct to represent the outer "Items" key:
type Items struct { Name string `json:"name"` Images map[string][]ImageUrl `json:"image_urls"` }
Here, the "image_urls" field is declared as a map where the keys are strings (representing image sizes) and the values are slices of ImageUrl structs.
ImageUrl Struct:
type ImageUrl struct { Url string `json:"url"` Width, Height int `json:"width,height"` }
This struct represents the individual image URL and its dimensions.
Usage:
To unmarshal the JSON into the Items struct, use:
var items Items json.Unmarshal(jsonData, &items)
Benefits of Using a Map:
The above is the detailed content of How to Handle JSON Responses with Dynamic Keys in Go?. For more information, please follow other related articles on the PHP Chinese website!