首頁 > 後端開發 > Golang > 主體

我如何解組 JSON 資料並將其儲存在 Go 中的結構中

PHPz
發布: 2024-02-11 19:48:08
轉載
803 人瀏覽過

我如何解组 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中文網其他相關文章!

相關標籤:
來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!