Home > Backend Development > Golang > How to Handle Dynamic JSON Keys During Unmarshaling in Go?

How to Handle Dynamic JSON Keys During Unmarshaling in Go?

Susan Sarandon
Release: 2024-12-07 13:02:13
Original
733 people have browsed it

How to Handle Dynamic JSON Keys During Unmarshaling in Go?

Dynamic Key Handling in JSON Unmarshaling: GoLang

In GoLang, unmarshaling JSON data into a struct can become challenging when the keys in the JSON are dynamic or cannot be directly mapped to a specific field in the struct. This article presents a solution to this issue by introducing the use of a map to capture dynamic keys and their associated values.

Problem Description:

Consider the following struct:

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

and a JSON string:

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

Using the standard JSON Unmarshal function with the struct would not capture the dynamic key, "any string".

Solution Using a Map:

To solve this issue, we can use a map to store the dynamic key-value pairs. Here's an example:

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

In this solution, the m variable will be a map where the keys are the dynamic strings, and the values are instances of the X struct.

This approach allows us to capture the dynamic keys and their corresponding values while still maintaining a structured representation of the data.

Playground Example:

The provided playground example demonstrates the use of the solution:

https://go.dev/play/p/tZ27zKhI9Ct

The above is the detailed content of How to Handle Dynamic JSON Keys During Unmarshaling 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