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
DDDOriginal
2024-12-11 02:58:09589browse

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"`
}

And a sample JSON string:

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

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)

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!

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