Home > Backend Development > Golang > How to Parse JSON with Dynamic Top-Level Keys in Go?

How to Parse JSON with Dynamic Top-Level Keys in Go?

Patricia Arquette
Release: 2024-12-30 22:49:14
Original
831 people have browsed it

How to Parse JSON with Dynamic Top-Level Keys in Go?

JSON Parsing with Dynamic Keys in Golang

In Golang, parsing a JSON string with a dynamic top-level key can be challenging. Consider the following JSON:

{"bvu62fu6dq": {
    "name": "john",
    "age": 23,
    .....
    .....}
Copy after login

To extract the values for "name" and "age," a custom solution is required as the top-level key is not a fixed field.

Using Go Structs and Maps

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

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

Decoding and Extraction

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

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!

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