In Go, handling dynamic JSON keys within struct fields can be challenging. Let's delve into this and provide a comprehensive solution using the Viper library.
Problem Statement
Consider a JSON config file with dynamic keys:
{ "things" :{ "123abc" :{ "key1": "anything", "key2" : "more" }, "456xyz" :{ "key1": "anything2", "key2" : "more2" }, "blah" :{ "key1": "anything3", "key2" : "more3" } } }
To parse this configuration into a struct, one might define:
type Thing struct { Name string `?????` Key1 string `json:"key2"` Key2 string `json:"key2"` }
However, the question arises: how can you unmarshal the dynamic keys as struct field names?
Solution
To handle dynamic keys, consider using a map:
type X struct { Things map[string]Thing } type Thing struct { Key1 string Key2 string }
Unmarshal like:
var x X if err := json.Unmarshal(data, &x); err != nil { // handle error }
Playground Example
If the key must be a member of the struct, you can use a loop to add it after unmarshalling:
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 }
Playground Example
Using these techniques, you can effectively unmarshal dynamic JSON keys into struct fields in Go, even when using libraries like Viper.
The above is the detailed content of How to Unmarshal Dynamic Viper or JSON Keys as Struct Fields in Go?. For more information, please follow other related articles on the PHP Chinese website!