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

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

Patricia Arquette
Release: 2024-11-19 01:26:02
Original
954 people have browsed it

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

Unmarshalling Dynamic JSON Keys into Struct Fields in Go

Dynamic JSON keys can pose a challenge when unmarshalling into structs with static field names. Consider the following JSON configuration file:

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

To represent this JSON in a Go struct, you can use a map instead of static field names:

type X struct {
    Things map[string]Thing
}

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

Then, unmarshal the JSON using the json.Unmarshal function:

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

With this approach, the dynamic keys become the keys of the map, allowing you to access the values as needed.

However, if the key must be a member of the Thing struct, you can write a loop to add the key after unmarshalling:

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 method allows you to have both the key as a field and the dynamic values.

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