Unmarshal JSON data of unknown format [duplicate]

99封情书 提交于 2019-12-18 09:51:52

问题


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 the struct 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!