登录
首页 >  Golang >  Go问答

Golang中如何解析并存储JSON数据的结构

来源:stackoverflow

时间:2024-02-07 10:00:24 335浏览 收藏

大家好,今天本人给大家带来文章《Golang中如何解析并存储JSON数据的结构》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

这是我在程序中使用 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 字段执行相同的操作。

理论要掌握,实操不能落!以上关于《Golang中如何解析并存储JSON数据的结构》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>