Decoding JSON with Variable Structure
When working with JSON data, it can be challenging to deal with data structures that vary. In such cases, conventional methods like json.Unmarshal() using fixed structs become impractical. Here's a solution for this scenario:
Solution:Unmarshal into map[string]interface{}
Instead of relying on predefined structs, we can unmarshal the JSON into a generic map[string]interface{} type. This allows us to handle JSON data with varying structures.
Consider the following JSON:
{ "votes": { "option_A": "3" } }
To add a "count" key to this JSON, we can unmarshal it as follows:
package main import ( "encoding/json" ) func main() { in := []byte(`{ "votes": { "option_A": "3" } }`) var raw map[string]interface{} if err := json.Unmarshal(in, &raw); err != nil { panic(err) } raw["count"] = 1 out, err := json.Marshal(raw) if err != nil { panic(err) } println(string(out)) }
This approach allows us to easily modify the JSON structure without being bound to a fixed data model. The map[string]interface{} type provides flexibility in handling dynamic JSON structures.
The above is the detailed content of How Can I Decode JSON with a Variable Structure in Go?. For more information, please follow other related articles on the PHP Chinese website!