Home > Backend Development > Golang > How Can I Unmarshal JSON with Arbitrary Key/Value Pairs into a Go Struct?

How Can I Unmarshal JSON with Arbitrary Key/Value Pairs into a Go Struct?

Susan Sarandon
Release: 2024-10-30 06:45:28
Original
1082 people have browsed it

How Can I Unmarshal JSON with Arbitrary Key/Value Pairs into a Go Struct?

Unmarshaling JSON with Arbitrary Key/Value Pairs to a Struct

Problem Statement

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.

Solution

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>
Copy after login

Unmarshaling Process

This JSON string:

<code class="json">{"known1": "foo", "known2": "bar", "unknown1": "car", "unknown2": 1}</code>
Copy after login

can be unmarshaled using the following steps:

  1. Create an instance of the Message struct.
  2. Unmarshal the JSON string into the struct.
  3. Iterate over the raw JSON object after unmarshaling and extract the keys and values of the unknown fields.
  4. Store each unknown key/value pair in a new map and append it to the Unknowns field in the struct.

Alternative Solution

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>
Copy after login

Conclusion

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template