Unable to append/overwrite JSON file (Go)

Good day everyone, I am a newbie to Go and am still learning the ropes, currently I am facing difficulties while making changes to a json file.

So I have a function that basically removes an element from the slice. I am unable to append the json file elsewhere except at one location. The “Done” will always get printed, any suggestions on this? Thank you :slight_smile:

func removeAppt(remove AppointmentsDetail) {
	bookedAppointmentsData := getBookedAppointmentsData() // Get the slice of data

	for i := 0; i < len(bookedAppointmentsData); i++ {
		bookedAppt := bookedAppointmentsData[i]
                //If matches input value removes it from slice and append to json
		if bookedAppt == remove {
			bookedAppointmentsData = append(bookedAppointmentsData[:i], bookedAppointmentsData[i+1:]...)
			i--
	
			bytes, err := json.MarshalIndent(bookedAppointmentsData, "", "  ")

			if err != nil {
				log.Fatalln(err)
			}

			_ = ioutil.WriteFile("bookedAppointments.json", bytes, 0644)

                        fmt.println("Done") //Always gets printed

			break
		}
	}

}

It keeps be printed because it is in the struct definition, AppointmentsDetail. I think you can set the ‘omitempty’ flag. For example

Done bool int json:",omitempty"

It is successfully finding the AppointmentDetail you want to remove; you know that because “Done” gets printed.

Is the file being created? I would check the returned value from the ioutil.WriteFile call.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.