Home > Backend Development > Golang > How do you unmarshal dynamic JSON keys with Viper and Go structs?

How do you unmarshal dynamic JSON keys with Viper and Go structs?

Mary-Kate Olsen
Release: 2024-11-20 11:33:02
Original
528 people have browsed it

How do you unmarshal dynamic JSON keys with Viper and Go structs?

Unmarshaling Dynamic JSON Keys with Viper and Go structs

In Go, handling JSON data with dynamic keys can be challenging. For instance, if you have a JSON configuration file with an object containing keys that vary in name, how do you unmarshal this data into a Go struct?

Let's take the following JSON configuration file as an example:

{
  "things" :{
    "123abc" :{
      "key1": "anything",
      "key2" : "more"
    },
    "456xyz" :{
      "key1": "anything2",
      "key2" : "more2"
    },
    "blah" :{
      "key1": "anything3",
      "key2" : "more3"
    }
  }
}
Copy after login

To address this, you can utilize a map to represent the dynamic keys, as shown in this updated Go struct:

type X struct {
    Things map[string]Thing
}

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

Once you have defined the struct, you can unmarshal the JSON data like this:

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

If the name of the object keys should be a field of the "Thing" struct, you can add a loop to assign it after unmarshaling:

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

Alternatively, a custom JSON decoder can be used to handle the dynamic keys by overriding the "Decode" method. Refer to the official Go documentation for more details on this approach.

With these techniques, you can effectively unmarshal dynamic JSON keys into Go structs, enabling you to work with complex configuration files and data structures.

The above is the detailed content of How do you unmarshal dynamic JSON keys with Viper and Go structs?. 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