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)
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)
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!