Home > Backend Development > Golang > How to Parse JSON with Known and Unknown Key/Value Pairs into a Go Struct?

How to Parse JSON with Known and Unknown Key/Value Pairs into a Go Struct?

DDD
Release: 2024-10-28 02:13:30
Original
475 people have browsed it

How to Parse JSON with Known and Unknown Key/Value Pairs into a Go Struct?

Unmarshal JSON with Arbitrary Key/Value Pairs to Struct

Problem

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).

Solution

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

Unmarshal the JSON string into this struct:

<code class="go">json.Unmarshal([]byte(jsonMsg), &msg)</code>
Copy after login

The Unknowns field will contain a list of maps representing the unknown key/value pairs.

Alternatives

  1. Double Unmarshal:

    • First, unmarshal into a temporary struct containing only the known fields.
    • Then, unmarshal again into a map[string]interface{} and extract the unknown values manually.
  2. Unmarshal and Type Conversion:

    • Unmarshal into a map[string]interface{}.
    • Iterate over the map and type assert the values to appropriate types.

Considerations

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!

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