Dynamic Key Parsing in JSON with Golang: Extracting Name and Age
To extract specific values from a JSON string with a dynamic key, a custom approach is required. Here's a breakdown of the solution:
First, we define a struct to represent the "Info" object within the JSON:
type Info map[string]Person
Next, we define the "Person" struct to hold the "name" and "age" fields:
type Person struct { Name string `json:"name"` Age int `json:"age"` }
Now, we can unmarshal the JSON string into an instance of the "Info" type:
var info Info if err := json.Unmarshal([]byte(j), &info); err != nil { // Handle error }
Once the JSON is unmarshaled, we can access the "name" and "age" fields dynamically:
fmt.Printf("%s: %d\n", info["bvu62fu6dq"].Name, info["bvu62fu6dq"].Age)
This approach allows you to extract values from JSON objects with dynamic keys, providing flexibility and adaptability in data parsing.
The above is the detailed content of How to Parse JSON with Dynamic Keys and Extract Specific Values in Go?. For more information, please follow other related articles on the PHP Chinese website!