When working with JSON payloads, it can be challenging to handle data with an unknown format. This situation arises when the keys and values within the JSON structure are not predefined. To address this, Go offers several approaches to unmarshaling unknown formats.
In the provided JSON data, the keys represent subjects, and the values are arrays of student grades. To unmarshal this data effectively, we can utilize the following techniques:
Option 1: Using map[string]interface{}
If the keys are entirely unknown, you can employ a map[string]interface{} to unmarshal the JSON payload. This method creates a map where the keys are strings, and the values are interfaces representing the unmarshaled data.
var grades map[string]interface{} err := json.Unmarshal([]byte(jsonString), &grades)
Option 2: Using a Custom Struct
If you have a specific structure you want to represent the data, you can create a custom struct and ignore the unknown keys during unmarshaling using the json:"-" tag. The Grades field in the GradeData struct will contain the unmarshaled data as a map[string]interface{}.
type GradeData struct { Grades map[string]interface{} `json:"-"` } gradesData := GradeData{} err := json.Unmarshal([]byte(jsonString), &gradesData.Grades)
By utilizing either of these approaches, you can effectively unmarshal JSON data of unknown format and access the data in Go. It is important to choose the method that best aligns with the requirements of your application.
The above is the detailed content of How to Unmarshal JSON Data with Unknown Keys and Values in Go?. For more information, please follow other related articles on the PHP Chinese website!