Home > Software engineering >  json.Unmarshal not work even though there is an export field
json.Unmarshal not work even though there is an export field

Time:12-18

json file:

{
  "student_class": [
    {
      "student_id": 1,
      "class_id": 2
    },
    {
      "student_id": 1,
      "class_id": 1
    },

Struct:

package studentClass

type StudentClasses struct {
    StudentClasses []StudentClass
}

type StudentClass struct {
    StudentId int `json:"student_id"`
    ClassId   int `json:"class_id"`
}

my function:

func Read() {
    var studentClasses studentClass.StudentClasses
    jsonFile, err := os.Open("db/student_class.json")
    if err != nil {
        fmt.Println(err)
    }
    defer jsonFile.Close()

    byteValue, _ := io.ReadAll(jsonFile)
    json.Unmarshal(byteValue, &studentClasses)

    for i := 0; i < len(studentClasses.StudentClasses); i   {
        fmt.Println(studentClasses.StudentClasses[i])
    }

}

It return nothing

When i add fmt.Println(studentClasses) after json.Unmarshall... then it return {[]} Error off json.Unmarshal is nil

I have researched about this problem but people with the same problem as me are saying that struct's field is not exported. Example: go json.Unmarshal do not working I do not know where the error is and what am I doing wrong Please help me to solve this problem. thanks everyone!

CodePudding user response:

You didn't specify the json name for StudentClasses.

type StudentClasses struct {
    StudentClasses []StudentClass `json:"student_class"`
}

Sample:

package main

import (
    "encoding/json"
    "fmt"
)

type StudentClasses struct {
    StudentClasses []StudentClass `json:"student_class,omitempty"`
}

type StudentClass struct {
    StudentId int `json:"student_id"`
    ClassId   int `json:"class_id"`
}

func main() {
    _json := `{
  "student_class": [
    {
      "student_id": 1,
      "class_id": 2
    },
    {
      "student_id": 1,
      "class_id": 1
    }
  ]
}`
    var studentClasses StudentClasses
    json.Unmarshal([]byte(_json), &studentClasses)

    fmt.Printf("% v", studentClasses)
}
  • Related