1

I'm trying to read from a file and load it into a struct slice. The lines that I read in are loaded correct as shown in the block comment.

The issue I'm having is that the class variable keeps coming back with empty values. What am I doing wrong?

func loadClasses(path string) []Class {
    var a []Class

    inFile, _ := os.Open(path)
    defer inFile.Close()
    scanner := bufio.NewScanner(inFile)
    scanner.Split(bufio.ScanLines)
    var class Class
    for scanner.Scan() {
        var err = json.Unmarshal(scanner.Bytes(), &class)

        if err != nil {
            fmt.Print("Error:", err)
        } else {
            a = append(a, class)
        }
    }
    return a
}

type Class struct {
    id   string
    name string
}

/*
Sample contents
"{"id":124997,"name":"Environmental Sciences"}
{"id":123905,"name":"Physical Education"}
{"id":127834,"name":"Mandarin"}
{"id":123507,"name":"Biology"}
{"id":123883,"name":"German"}
{"id":129148,"name":"German"}
{"id":123545,"name":"Spanish"}"

*/

Thank you to ivan.sim for the help. My issue was two part, the struct members had to be capitalized and I was missing the json: "id" and json: "name"

Leighner
  • 193
  • 1
  • 11

1 Answers1

7

You can export the fields in your Class struct by changing the first letter of the fields to upper case like this:

type Class struct{
  Id string
  Name string
}

Optionally, you can also add tags to the fields like this:

type Class struct{
  Id string `json: "id"`
  Name string `json: "name"`
}

More information on how the json package handles encoding and decoding can be found in the json.Marshal and json.Unmarshal docs respectively.

ivan.sim
  • 8,972
  • 8
  • 47
  • 63
  • Close: second one won't work, because `reflect` and therefore `encoding/json` simply can't see fields with lowercase names. You want to use the field names from the first code snippet, but with struct tags saying they should be filled in from the lowercase key names in the input. – twotwotwo Aug 08 '15 at 23:47
  • @twotwotwo Fixed. Thanks! – ivan.sim Aug 09 '15 at 00:02