Write a JSON file -- you can do so in VSC (create a file xxx.json) -- containing data about 3 fictional Bi-Co students. The file should contain at least the following information for each student:
jsonFile, err := os.Open("bico.json") if err != nil { fmt.Println(err) } fmt.Println("Successfully Opened bico.json") byteValue, _ := ioutil.ReadAll(jsonFile) jsonFile.Close()My experience with opening files is that if you use the the "run" button in VSC, you need to give the full, absolute path to the file being opened. If you use a terminal window and type "go run xx.go" then you can use a relative path name. (As a aside, what "go run ..." actually seems to do is to run "go build ..." and put the compiled executable into a file somewhere in the /tmp directory and then run that compiled file. When VSC does this, it actually seems to switch the current directory away from where the source is. Hence, the need to use absolute paths. ) Once read, the simplest thing to do is to unmarshal the byte array into a slice of maps. To do so create two types
type jsonMap map[string]interface{} type jsonSlice []jsonMapthen after the read function add the following lines:
var res jsonSlice json.Unmarshal(byteValue, &res)Done. You have read in the JSON file. Add a print statement to verify that you have succeeded.
Create structs as needed to read your student data file. You may want to update the representation in your JSON to make this easier. Then adjust your code to read the JSON into a slice of structs.
One important thing when you are creating structs for unmarshalling. The variable names inside the structs MUST have an initial capital letter. Why?
data, _ := json.Marshal(students) fmt.Println(string(data))The resulting JSON should be fairly similar to your student file.