Home >Backend Development >Golang >How to Unmarshal a JSON Map into a Go Struct with Custom Handling?
In Go, unmarshaling involves converting JSON data into a Go data structure. While the basic principles of unmarshaling are straightforward, specific scenarios, like populating a map, might need custom handling.
A common problem encountered is trying to unmarshal a map into a Go struct. Consider the following example:
<code class="go">type OHLC_RESS struct { Pair map[string][]Candles Last int64 `json:"last"` } // Candles represents individual candlesticks within the map. type Candles struct { // ... Time, Open, High, Low, Close, VWAP, Volume, Count fields omitted }</code>
On attempting to unmarshal JSON data with the above struct, the Last field is populated successfully, but the Pair map remains empty.
The default unmarshaling process in Go uses field names and tags to match JSON keys. However, in this case, the Pair map needs custom handling as its key names are not known in advance. To achieve this, implement the json.Unmarshaler interface for the OHLC_RESS struct:
<code class="go">func (r *OHLC_RESS) UnmarshalJSON(d []byte) error { // Decode only the object's keys and leave values as raw JSON. var obj map[string]json.RawMessage if err := json.Unmarshal(d, &obj); err != nil { return err } // Decode the "last" element into the Last field. if last, ok := obj["last"]; ok { if err := json.Unmarshal(last, &r.Last); err != nil { return err } delete(obj, "last") } // Decode the remaining elements into the Pair map. r.Pair = make(map[string][]Candles, len(obj)) for key, val := range obj { cc := []Candles{} if err := json.Unmarshal(val, &cc); err != nil { return err } r.Pair[key] = cc } return nil }</code>
This custom unmarshaling function separates the decoding process into steps. It first decodes the object's keys, then handles the "last" element separately, and finally, it decodes the remaining elements into the Pair map. This approach grants control over the decoding process and allows for custom handling of specific fields like the Pair map.
The above is the detailed content of How to Unmarshal a JSON Map into a Go Struct with Custom Handling?. For more information, please follow other related articles on the PHP Chinese website!