Home > Backend Development > Golang > How Can I Unmarshal JSON with a Dynamic Key in Go?

How Can I Unmarshal JSON with a Dynamic Key in Go?

DDD
Release: 2024-12-11 02:58:09
Original
590 people have browsed it

How Can I Unmarshal JSON with a Dynamic Key in Go?

Dynamic Key Unmarshaling in JSON with Go

When working with JSON data, it can be challenging to unmarshal into a struct if one of the keys is dynamic and cannot be directly mapped to a field name in the struct. To address this, a practical solution can be found in Golang.

Given a defined struct:

type X struct {
  A string `json:"a_known_string"`
  B string `json:"b_known_string"`
}
Copy after login

And a sample JSON string:

{
  "any string": {
    "a_known_string": "some value",
    "b_known_string": "another value"
  }
}
Copy after login

To capture both the known and dynamic key in the JSON, a map can be utilized:

var m map[string]X
err := json.Unmarshal([]byte(jsnStr), &m)
Copy after login

This approach allows for the storage of multiple objects under a single dynamic key, providing flexibility in data handling.

An example playground can be found [here](https://play.golang.org/p/jh-GAlUEo7n).

The above is the detailed content of How Can I Unmarshal JSON with a Dynamic Key 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template