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 isim 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"
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.