Dynamic Key Handling in Viper/JSON Unmarshaling
When dealing with JSON data that deviates from a predetermined format, unmarshalling in Go can be challenging. Consider a JSON configuration file with dynamic keys, such as the following:
{ "things" :{ "123abc" :{ "key1": "anything", "key2" : "more" }, "456xyz" :{ "key1": "anything2", "key2" : "more2" }, "blah" :{ "key1": "anything3", "key2" : "more3" } } }
To unmarshal this data into a Go struct with dynamic keys, one approach is to utilize a map:
type X struct { Things map[string]Thing } type Thing struct { Key1 string Key2 string }
By using map[string]Thing, the resulting struct can handle any number of dynamic keys. Unmarshal the data using:
var x X if err := json.Unmarshal(data, &x); err != nil { // handle error }
This approach allows for straightforward unmarshalling of dynamic keys in both JSON and Viper (using viper.Get("things") to obtain an array of Thing values).
However, if the key itself must be a member of the struct, a post-unmarshalling loop can be employed to update the fields:
type Thing struct { Name string `json:"-"` // add the field Key1 string Key2 string } // Fix the name field after unmarshal for k, t := range x.Things { t.Name = k x.Things[k] = t }
This allows the key to be incorporated into the struct while preserving the original dynamic nature of the JSON data.
The above is the detailed content of How to Unmarshal JSON with Dynamic Keys in Go?. For more information, please follow other related articles on the PHP Chinese website!