Home >Backend Development >Golang >How to Parse JSON with Known and Unknown Key/Value Pairs into a Go Struct?
How can I parse a JSON string with known and unknown key/value pairs into a Go struct? The unknown fields can have any name and value type (string, bool, float64, or int).
Create a struct with the known fields and a slice of maps for the unknown fields:
<code class="go">type Message struct { Known1 string `json:"known1"` Known2 string `json:"known2"` Unknowns []map[string]interface{} }</code>
Unmarshal the JSON string into this struct:
<code class="go">json.Unmarshal([]byte(jsonMsg), &msg)</code>
The Unknowns field will contain a list of maps representing the unknown key/value pairs.
Double Unmarshal:
Unmarshal and Type Conversion:
All three solutions are valid, but the simplest and most elegant is the initial struct-based approach. It avoids the need for additional unmarshals or manual type conversions.
The above is the detailed content of How to Parse JSON with Known and Unknown Key/Value Pairs into a Go Struct?. For more information, please follow other related articles on the PHP Chinese website!