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).
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.
Double Unmarshal:
Unmarshal and Type Conversion:
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.
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