Home >Backend Development >Golang >How to Unmarshal JSON with a Dynamic Key in Go?
JSON Unmarshal with Dynamic Key
Unmarshalling JSON with a dynamic key that cannot be captured as a static field in a struct can be achieved in Go using a map.
Example:
Consider the following JSON data:
{ "any string" : { "a_known_string" : "some value", "b_known_string" : "another value" } }
And the struct:
type X struct { A string `json:"a_known_string"` B string `json:"b_known_string"` }
Solution:
To capture the dynamic key as well as the known values, use a map instead of a struct:
import "encoding/json" var m map[string]X err := json.Unmarshal([]byte(jsonStr), &m) if err != nil { // Handle error } // Access the data using the dynamic key dynamicKeyData := m["any string"]
In this scenario, the map[string]X type allows for the dynamic key "any string" to be captured along with the known values in the X struct.
The above is the detailed content of How to Unmarshal JSON with a Dynamic Key in Go?. For more information, please follow other related articles on the PHP Chinese website!