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

How to Unmarshal JSON with a Dynamic Key in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-09 12:16:15553browse

How to Unmarshal JSON with a Dynamic Key in Go?

JSON Unmarshal with Dynamic Key

Unmarshalling JSON with a dynamic key that cannot be captured as a static field in a struct can be achieved in Go using a map.

Example:

Consider the following JSON data:

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

And the struct:

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

Solution:

To capture the dynamic key as well as the known values, use a map instead of a struct:

import "encoding/json"

var m map[string]X
err := json.Unmarshal([]byte(jsonStr), &m)
if err != nil {
    // Handle error
}

// Access the data using the dynamic key
dynamicKeyData := m["any string"]

In this scenario, the map[string]X type allows for the dynamic key "any string" to be captured along with the known values in the X struct.

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