How to Unmarshal JSON with Arbitrary Key/Value Pairs into a Struct in Go?

DDD
Release: 2024-10-26 16:35:30
Original
824 people have browsed it

How to Unmarshal JSON with Arbitrary Key/Value Pairs into a Struct in Go?

Unmarshal JSON with Arbitrary Key/Value Pairs to Struct

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.

Problem Statement

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

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.

Proposed Solution

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

With this struct, the sample JSON message should yield the following result:

{Known1:foo Known2:bar Unknowns:[map[unknown1:car] map[unknown2:1]]}
Copy after login

Alternative Solution

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

This will produce:

<nil>
map[known1:foo known2:bar unknown1:car unknown2:1]
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template