我如何解組 JSON 資料並將其儲存在 Go 中的結構中
php小編草莓分享一種解組JSON資料並將其儲存在Go語言結構中的方法。 JSON是一種常用的資料交換格式,Go語言提供了方便的解析和處理JSON資料的工具包。透過使用Go語言內建的"json"包,我們可以輕鬆地將JSON資料解組成對應的結構體,並進行儲存和處理。這種方法簡單易懂,能夠幫助開發者有效率地處理JSON數據,提升開發效率。下面我們來詳細介紹如何使用Go語言解組JSON數據,並將其儲存在結構體中。
問題內容
這是我在程式中使用 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 欄位執行相同的操作。
以上是我如何解組 JSON 資料並將其儲存在 Go 中的結構中的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Go語言中使用RedisStream實現消息隊列時類型轉換問題在使用Go語言與Redis...

GoLand中自定義結構體標籤不顯示怎麼辦?在使用GoLand進行Go語言開發時,很多開發者會遇到自定義結構體標籤在�...

Go爬蟲Colly中的Queue線程問題探討在使用Go語言的Colly爬蟲庫時,開發者常常會遇到關於線程和請求隊列的問題。 �...

Go語言中字符串打印的區別:使用Println與string()函數的效果差異在Go...

Go語言中用於浮點數運算的庫介紹在Go語言(也稱為Golang)中,進行浮點數的加減乘除運算時,如何確保精度是�...

Go語言中哪些庫是大公司開發或知名開源項目?在使用Go語言進行編程時,開發者常常會遇到一些常見的需求,�...

Go語言中結構體定義的兩種方式:var與type關鍵字的差異Go語言在定義結構體時,經常會看到兩種不同的寫法:一�...
