"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-07
Browse:636

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:

type Message struct {
    Known1   string `json:"known1"`
    Known2   string `json:"known2"`
    Unknowns []map[string]interface{}
}

Unmarshal the JSON string into this struct:

json.Unmarshal([]byte(jsonMsg), &msg)

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3