Home >Backend Development >Golang >How to Unmarshal JSON with Dynamic Keys into Struct Fields in Go?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-16 00:07:03598browse

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
}

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
}

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
}

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!

Statement:
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