Many similar questions have been asked regarding unmarshalling JSON with unknown/arbitrary key/value pairs into a struct. However, none of the solutions found provided a simple and elegant method to achieve this.
We have a JSON string containing known fields (always present) and an unknown number of unknown/arbitrary fields. Example:
<code class="json">{"known1": "foo", "known2": "bar", "unknown1": "car", "unknown2": 1}</code>
In this example, known1 and known2 are known fields, while unknown1 and unknown2 are arbitrary fields. The unknown fields can have any name (key) and value (string, bool, float64, or int).
Our goal is to find an idiomatic way to parse such a JSON message into a struct.
We can define the following struct:
<code class="go">type Message struct { Known1 string `json:"known1"` Known2 string `json:"known2"` Unknowns []map[string]interface{} }</code>
With this struct, the sample JSON message should yield the following result:
{Known1:foo Known2:bar Unknowns:[map[unknown1:car] map[unknown2:1]]}
Another option is to unmarshal the JSON into a map[string]interface{}:
<code class="go">import ( "encoding/json" "fmt" ) func main() { jsonMsg := `{"known1": "foo", "known2": "bar", "unknown1": "car", "unknown2": 1}` var msg map[string]interface{} fmt.Println(json.Unmarshal([]byte(jsonMsg), &msg)) fmt.Printf("%+v", msg) }</code>
This will produce:
<nil> map[known1:foo known2:bar unknown1:car unknown2:1]
The advantage of this approach is that we can iterate over the keys and values and perform necessary type assertions to handle the data. We may or may not populate a struct with the data depending on our needs.
The above is the detailed content of How to Unmarshal JSON with Arbitrary Key/Value Pairs into a Struct in Go?. For more information, please follow other related articles on the PHP Chinese website!