Home > Backend Development > Golang > How to Parse JSON with Dynamic Keys and Extract Specific Values in Go?

How to Parse JSON with Dynamic Keys and Extract Specific Values in Go?

Barbara Streisand
Release: 2024-12-29 12:27:18
Original
981 people have browsed it

How to Parse JSON with Dynamic Keys and Extract Specific Values in Go?

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
Copy after login

Next, we define the "Person" struct to hold the "name" and "age" fields:

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}
Copy after login

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
}
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template