这是我在程序中使用 go struct 存储的 json 测试数据
[ { "id": 393, "question": "the "father" of mysql is ______.", "description": null, "answers": { "answer_a": "bill joy", "answer_b": "stephanie wall", "answer_c": "bill gates", "answer_d": "michael widenius", "answer_e": null, "answer_f": null }, "multiple_correct_answers": "false", "correct_answers": { "answer_a_correct": "false", "answer_b_correct": "false", "answer_c_correct": "false", "answer_d_correct": "true", "answer_e_correct": "false", "answer_f_correct": "false" }, "correct_answer": "answer_a", "explanation": null, "tip": null, "tags": [ { "name": "mysql" } ], "category": "sql", "difficulty": "medium" } ]
这是我编写的用于存储数据的函数,但无法获得正确的响应,而不是在打印时得到一个空白结构
func FetchQuiz(num int, category string) { // write code to read json file jsonFile, err := os.Open("test.json") if err != nil { fmt.Println(err) } defer jsonFile.Close() byteValue, _ := ioutil.ReadAll(jsonFile) fmt.Println(string(byteValue)) type Data struct { ID int Question string Description string Answers struct { A string B string C string D string E string F string } MultipleCorrectAnswers string CorrectAnswers struct { A string B string C string D string E string F string } CorrectAnswer string Explanation string Tip string Tags []struct { Name string } Category string Difficulty string } var QuizList2 []Data if err := json.Unmarshal(byteValue, &QuizList2); err != nil { fmt.Println(err.Error()) } fmt.Println(QuizList2)
但得到的响应是[{393 mysql的“父亲”是______。 { } { } [{mysql}] sql medium}]我已经尝试了一切方法来解决它,但没有达到响应
json 字段 answer_a
不会单独映射到 go 字段 a
。
更改 go 字段的名称以匹配 json 字段的名称(忽略大小写):
answer_a string
或者在您的字段中使用 go struct 标记:
A string `json:"answer_a"`
对与相应 json 字段不匹配的其余 go 字段执行相同的操作。