The objective is to unmarshal a JSON string containing a mix of known and unknown key/value pairs into a Go struct. The known fields should be unmarshaled to specific struct fields, while the unknown fields should be stored as a collection of key/value pairs within the struct.
To achieve this, a struct can be defined with a combination of known fields and a slice of maps:
<code class="go">type Message struct { Known1 string `json:"known1"` Known2 string `json:"known2"` Unknowns []map[string]interface{} }</code>
This JSON string:
<code class="json">{"known1": "foo", "known2": "bar", "unknown1": "car", "unknown2": 1}</code>
can be unmarshaled using the following steps:
Alternatively, instead of using a struct, the JSON can be unmarshaled directly into a map[string]interface{}, which will provide access to all key/value pairs as a dynamic collection.
<code class="go">var msg map[string]interface{} json.Unmarshal([]byte(jsonMsg), &msg)</code>
The choice between using a struct or a map depends on the specific requirements of the application. If predefined known fields and a structured approach are desired, a struct is suitable. If the exact nature of the unknown fields is not known in advance, or if a more flexible dynamic data structure is required, a map is a viable option.
The above is the detailed content of How Can I Unmarshal JSON with Arbitrary Key/Value Pairs into a Go Struct?. For more information, please follow other related articles on the PHP Chinese website!