0

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!

Stupid dev
  • 29
  • 4
  • 2
    Hello, welcome to SO! Go doesn't throw exceptions, so it is fundamentally important to ALWAYS check for errors. Start by checking the errors in io.ReadAll() and json.Unmarshal(), checking errors will help you. Simplest possible: `if err := foo(); err != nil { return err }` and the caller (say `main()` should do something like `if err := myfunc(..); err != nil { fmt.Fprint(os.Stderr, err) os.Exit(1) } }` – marco.m Dec 17 '22 at 17:36
  • 2
    `StudentClasses` != `student_class`, you need an explicit struct tag for that field as well. *"Unmarshal matches incoming object keys to the keys used by Marshal (either the struct field name or its tag), **preferring an exact match but also accepting a case-insensitive match**"* -- Your JSON key is missing the `es` plural suffix and includes a `_`, that is not gonna match the field's name. – mkopriva Dec 17 '22 at 17:37

1 Answers1

0

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)
}
Cetin Basoz
  • 22,495
  • 3
  • 31
  • 39