Unmarshalling Dynamic JSON Keys into Struct Fields in Go
Dynamic JSON keys can pose a challenge when unmarshalling into structs with static field names. Consider the following JSON configuration file:
{ "things" :{ "123abc" :{ "key1": "anything", "key2" : "more" }, "456xyz" :{ "key1": "anything2", "key2" : "more2" }, "blah" :{ "key1": "anything3", "key2" : "more3" } } }
To represent this JSON in a Go struct, you can use a map instead of static field names:
type X struct { Things map[string]Thing } type Thing struct { Key1 string Key2 string }
Then, unmarshal the JSON using the json.Unmarshal function:
var x X if err := json.Unmarshal(data, &x); err != nil { // handle error }
With this approach, the dynamic keys become the keys of the map, allowing you to access the values as needed.
However, if the key must be a member of the Thing struct, you can write a loop to add the key 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 }
This method allows you to have both the key as a field and the dynamic values.
The above is the detailed content of How to Unmarshal Dynamic JSON Keys into Struct Fields in Go?. For more information, please follow other related articles on the PHP Chinese website!