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

How to Unmarshal JSON with Dynamic Keys in Go?

Mary-Kate Olsen
Release: 2024-12-01 19:25:20
Original
318 people have browsed it

How to Unmarshal JSON with Dynamic Keys in Go?

Dynamic Key Handling in Viper/JSON Unmarshaling

When dealing with JSON data that deviates from a predetermined format, unmarshalling in Go can be challenging. Consider a JSON configuration file with dynamic keys, such as the following:

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

To unmarshal this data into a Go struct with dynamic keys, one approach is to utilize a map:

type X struct {
    Things map[string]Thing
}

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

By using map[string]Thing, the resulting struct can handle any number of dynamic keys. Unmarshal the data using:

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

This approach allows for straightforward unmarshalling of dynamic keys in both JSON and Viper (using viper.Get("things") to obtain an array of Thing values).

However, if the key itself must be a member of the struct, a post-unmarshalling loop can be employed to update the fields:

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

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

This allows the key to be incorporated into the struct while preserving the original dynamic nature of the JSON data.

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