Unmarshalling JSON with Dynamic Array Structure
When retrieving JSON data from third-party sources, the data structure can vary, sometimes containing arrays and sometimes not. This can pose challenges when using Go's json.Unmarshal function, as it expects a specific struct to match the JSON structure.
A common approach to handling this is to create a secondary struct with a slice, such as:
type ResponseWithSlice struct { Gwrcmds struct { Gwrcmd []struct { // Nested struct now a slice Gcmd string Gdata struct { Gip struct { Version string } } } } }
This works, but it involves duplicating the struct, which can be cumbersome.
A more versatile solution involves using json.RawMessage:
type Response struct { RawGwrcmd json.RawMessage `json:"gwrcmds"` }
With this approach, the gwrcmds field is stored as a raw JSON message, allowing us to peek into it and unmarshal it accordingly:
func (r *Response) UnmarshalJSON(b []byte) error { if err := json.Unmarshal(b, &r.RawGwrcmd); err != nil { return err } if r.RawGwrcmd[0] == '[' { // Check if it's an array return json.Unmarshal(r.RawGwrcmd, &r.Gwrcmds.Gwrcmd) } return json.Unmarshal(r.RawGwrcmd, &r.Gwrcmds.Gwrcmd) // Otherwise, treat it as a single struct }
This method allows us to handle both array and non-array structures without the need for additional structs.
The above is the detailed content of How to Efficiently Unmarshal JSON with Dynamic Array Structures in Go?. For more information, please follow other related articles on the PHP Chinese website!