How to Unmarshal JSON with Dynamic Keys into Struct Fields in Go?

Mary-Kate Olsen
Release: 2024-11-16 00:07:03
Original
518 people have browsed it

How to Unmarshal JSON with Dynamic Keys into Struct Fields in Go?

Unmarshalling Dynamic Keys into Struct Fields in Go

When working with JSON data that doesn't adhere to a predetermined structure, unmarshalling becomes more challenging. In this case, you have a JSON config file with dynamic keys within an object named "things".

To address this, one solution is to use a map within your struct to capture the dynamic keys. Here's an example:

type X struct {
    Things map[string]Thing
}

type Thing struct {
    Key1 string
    Key2 string
}
Copy after login

Instead of defining a specific struct field for each key, the "Things" field is a map that stores key-value pairs, where the key is the dynamic key.

To unmarshal the JSON data using this approach, you would do something like:

var x X
if err := json.Unmarshal(data, &x); err != nil {
    // handle error
}
Copy after login

This will unmarshal the JSON into the "X" struct, with the dynamic keys mapped to the appropriate struct instances within the "Things" map.

However, if you still want to have the key value as a field in the struct rather than part of the map key, you can use this approach:

type Thing struct {
    Name string `json:"-"` // <-- add this field
    Key1 string
    Key2 string
}

...

// Update the name field after unmarshalling
for k, t := range x.Things {
    t.Name = k
    x.Things[k] = t
}
Copy after login

This involves adding a "-`json" tag to the "Name" field to ignore it during unmarshalling. After unmarshalling, a loop is used to assign the dynamic keys to the "Name" field of each struct instance in the map.

The above is the detailed content of How to Unmarshal JSON with Dynamic Keys into Struct Fields 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