How to Unmarshal Unexpected JSON Structures in Go?

Susan Sarandon
Release: 2024-11-25 12:11:15
Original
859 people have browsed it

How to Unmarshal Unexpected JSON Structures in Go?

Unmarshaling JSON Data of Unknown Format

When faced with JSON data that possesses an unpredictable structure and variable keys, it presents the challenge of unmarshaling it into Go structures. This article addresses how to handle such scenarios efficiently.

Solution

To tackle this issue, there are two recommended approaches:

Approach 1: Using a Map

When the keys are unknown, utilizing a map[string]interface{} variable is a suitable option for unmarshaling the JSON payload.

var grades map[string]interface{}

err := json.Unmarshal([]byte(jsonString), &grades)
Copy after login

Here, the map variable "grades" will contain the unmarshaled data, where keys represent the unknown subject names, and values are maps consisting of student names and their grades.

Approach 2: Ignoring Unknown Keys with JSON Tag

If a struct is preferred, it can be annotated with the json:"-" tag to ignore specific fields during JSON marshaling and unmarshaling. This allows the struct to hold the unmarshaled data while excluding the unknown keys.

type GradeData struct {
    Grades map[string]interface{} `json:"-"`
}

var gradesData GradeData
err := json.Unmarshal([]byte(jsonString), &gradesData.Grades)
Copy after login

In this case, the struct "GradeData" contains only the "Grades" field, which is a map of subject names and student grades, but the original key names from the JSON are not present. The JSON tag ensures that the struct's fields align with the desired output format.

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