Unmarshalling JSON into Interfaces in Go
Consider the scenario where you have a JSON string with varied data structures depending on a specific field, such as the "cmd" field. You want to unmarshal this JSON into a Go struct containing a field with an interface{} type and adapt it to different data structures based on the "cmd" value.
Solution
To achieve this, define a base struct with fixed fields and a json.RawMessage field to hold the variant data. Then, create specific struct types for each variant and unmarshal to them based on the command.
For example:
type Message struct { Cmd string `json:"cmd"` Data json.RawMessage } type CreateMessage struct { Conf map[string]int `json:"conf"` Info map[string]int `json:"info"` } func main() { var m Message if err := json.Unmarshal(data, &m); err != nil { log.Fatal(err) } switch m.Cmd { case "create": var cm CreateMessage if err := json.Unmarshal([]byte(m.Data), &cm); err != nil { log.Fatal(err) } fmt.Println(m.Cmd, cm.Conf, cm.Info) default: log.Fatal("bad command") } }
In this example, the Message struct represents the overall message structure, containing the "cmd" field and a json.RawMessage field to hold the variant data. CreateMessage is a specific struct type representing the "create" command variant.
The code unmarshals the initial JSON string into a Message variable and then uses the "cmd" field to determine which specific variant to unmarshal and print.
The above is the detailed content of How to Unmarshal JSON into Go Interfaces Based on a Dynamic Field Value?. For more information, please follow other related articles on the PHP Chinese website!