Home > Software engineering >  How i can unmarshal JSON data as it is to store it in struct in Go
How i can unmarshal JSON data as it is to store it in struct in Go

Time:01-22

This is the JSON test data I used in my program to store using Go struct

[
  {
    "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"
  }
]

this is the function I wrote to store data but unable to get the proper response instead of that I'm getting a blank struct when printing it

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)

but getting response as [{393 The "father" Of MySQL Is ______. { } { } [{MySQL}] SQL Medium}]i have tried everything to solve it but not reached to the response

CodePudding user response:

JSON field answer_a will not map to Go field A by itself.

Either change the Go field's name to match the JSON field's name (ignoring case):

Answer_A string

Or use Go struct tags in your fields:

A string `json:"answer_a"`

Do the same for the rest of the Go fields that don't match their corresponding JSON fields.

  • Related