In Golang, parsing a JSON string with a dynamic top-level key can be challenging. Consider the following JSON:
{"bvu62fu6dq": { "name": "john", "age": 23, ..... .....}
To extract the values for "name" and "age," a custom solution is required as the top-level key is not a fixed field.
An optimal approach is to define a struct to represent the inner object and a map to represent the dynamic top-level key. The struct should include fields for the desired attributes, such as:
type Person struct { Name string `json:"name"` Age int `json:"age"` }
The map, in turn, can use the dynamic top-level key as the key and the Person struct as the value. This structure allows for efficient access to the desired values:
type Info map[string]Person
To decode the JSON into the custom structs, use the json.Unmarshal function. Once decoded, the values can be accessed via the map key:
var info Info json.Unmarshal([]byte(j), &info) fmt.Printf("%s: %d\n", info["bvu62fu6dq"].Name, info["bvu62fu6dq"].Age)
This approach provides a flexible and extensible way of handling JSON with dynamic top-level keys, ensuring easy access to the desired attributes.
The above is the detailed content of How to Parse JSON with Dynamic Top-Level Keys in Go?. For more information, please follow other related articles on the PHP Chinese website!