问题
My JSON is in the following format:
{
'Math':
[
{'Student1': 100.0, 'timestamp': Timestamp('2017-06-26 15:30:00'), 'Student2': 100.0, 'Student3': 97.058823442402414},
{'Student1': 93.877550824911907, 'timestamp': Timestamp('2017-06-26 15:31:00'), 'Student2': 100.0, 'Student5': 100.0},
{'Student8': 100.0, 'timestamp': Timestamp('2017-06-26 15:32:00'), 'Student10': 100.0, 'Student4': 100.0}
],
'English': [
{'Student1': 100.0, 'timestamp': Timestamp('2017-06-26 15:30:00'), 'Student5': 100.0, 'Student3': 97.058823442402414},
{'Student1': 93.877550824911907, 'timestamp': Timestamp('2017-06-26 15:31:00'), 'Student2': 100.0, 'Student5': 100.0},
{'Student8': 100.0, 'timestamp': Timestamp('2017-06-26 15:32:00'), 'Student10': 100.0, 'Student4': 100.0}
]
}
The keys are completely unknown to me. All I know is that the JSON will be of the format:
{
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(...)}]
}
where the subjects
, student_names
are all unknown and could vary.
I want to unmarshal this into a GoLang struct so I can return it to my front-end as a JSON object. What should my struct look like? This is what I tried, but it didn't work.
type GradeData struct {
Grades map[string]interface{} `json:"-"`
}
回答1:
- If you don't know the keys, you can use
map[string]interface{}
to unmarshal your JSON payload. - If you use
json:"-"
tag for thestruct
fields, those fields will be ignored during JSON Marshal/Unmarshal.
You can try following options: Go Playground link
Option 1:
var grades map[string]interface{}
err := json.Unmarshal([]byte(jsonString), &grades)
fmt.Println(err)
fmt.Printf("%#v\n", grades)
Option 2: if you want have struct
var gradesData GradeData
err := json.Unmarshal([]byte(jsonString), &gradesData.Grades)
fmt.Println(err)
fmt.Printf("%#v\n", gradesData)
来源:https://stackoverflow.com/questions/44773082/unmarshal-json-data-of-unknown-format