Home > Backend Development > Golang > How to Unmarshal Unknown JSON Data Structures in Go?

How to Unmarshal Unknown JSON Data Structures in Go?

Susan Sarandon
Release: 2024-11-26 01:15:15
Original
550 people have browsed it

How to Unmarshal Unknown JSON Data Structures in Go?

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(...)}]
}
Copy after login

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)
Copy after login

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)
Copy after login

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!

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