Unmarshal JSON Data of Unknown Format
The provided JSON follows a specific pattern:
{ SUBJECT1: [{Student_Name1: Grade, Student_Name2: Grade, ... , Student_Name3: Grade, timestamp: Timestamp(...)}], SUBJECT2: [{Student_Name4: Grade, Student_Name6: Grade, ... , Student_Name5: Grade, timestamp: Timestamp(...)}] ... SUBJECTN: [{Student_Name1: Grade, Student_Name6: Grade, ... , Student_Name9: Grade, timestamp: Timestamp(...)}] }
Goal: Unmarshal the JSON into a GoLang struct for return as a JSON object.
Solution:
Option 1: Using map[string]interface{}
Since the JSON keys are unknown, we can use map[string]interface{} to unmarshal the payload.
var grades map[string]interface{} err := json.Unmarshal([]byte(jsonString), &grades) fmt.Println(err) fmt.Printf("%#v\n", grades)
Option 2: Using a Struct
If a struct is desired, use the json:"-" tag to ignore fields during JSON marshalling/unmarshalling.
type GradeData struct { Grades map[string]interface{} `json:"-"` } err := json.Unmarshal([]byte(jsonString), &gradesData.Grades) fmt.Println(err) fmt.Printf("%#v\n", gradesData)
The above is the detailed content of How to Unmarshal Unknown JSON Data Structures in Go?. For more information, please follow other related articles on the PHP Chinese website!