Home > Article > Backend Development > How do you unmarshal dynamic JSON keys with Viper and Go structs?
Unmarshaling Dynamic JSON Keys with Viper and Go structs
In Go, handling JSON data with dynamic keys can be challenging. For instance, if you have a JSON configuration file with an object containing keys that vary in name, how do you unmarshal this data into a Go struct?
Let's take the following JSON configuration file as an example:
{ "things" :{ "123abc" :{ "key1": "anything", "key2" : "more" }, "456xyz" :{ "key1": "anything2", "key2" : "more2" }, "blah" :{ "key1": "anything3", "key2" : "more3" } } }
To address this, you can utilize a map to represent the dynamic keys, as shown in this updated Go struct:
type X struct { Things map[string]Thing } type Thing struct { Key1 string Key2 string }
Once you have defined the struct, you can unmarshal the JSON data like this:
var x X if err := json.Unmarshal(data, &x); err != nil { // handle error }
If the name of the object keys should be a field of the "Thing" struct, you can add a loop to assign it after unmarshaling:
// Fix the name field after unmarshal for k, t := range x.Things { t.Name = k x.Things[k] = t }
Alternatively, a custom JSON decoder can be used to handle the dynamic keys by overriding the "Decode" method. Refer to the official Go documentation for more details on this approach.
With these techniques, you can effectively unmarshal dynamic JSON keys into Go structs, enabling you to work with complex configuration files and data structures.
The above is the detailed content of How do you unmarshal dynamic JSON keys with Viper and Go structs?. For more information, please follow other related articles on the PHP Chinese website!