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
Release: 2024-12-09 12:16:15
Original
557 people have browsed it

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" 
 }
}
Copy after login

And the struct:

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

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"]
Copy after login

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!

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