I'm new to Go and I'm having a problem with my code concerning using json.Unmarshal multiple times within a for loop.
In this code, the first two functions fetch a response from a url, convert it to byte format, and then unmarshal it to data. The final function iterates over a list of url's, and should unmarshal them in turn, appending an array with a set of flight codes each time.
Using the set of structs as I've used here, I'm able to use getFlightData for a single url, which will print a set of flight codes. However when attempting the same within a for loop, the array flightsToSunnyCities will print a set of square brackets with empty space inside. Printing thisNumber within the for loop as it iterates will similarly print empty space.
var data ScheduledFlight
func UnmarshalBodyToPointerFlight(Body []byte, welcome *ScheduledFlight) {
err2 := json.Unmarshal(Body, &welcome)
if err2 != nil {
fmt.Println(err2)
os.Exit(1)
}
}
func GetFlightData(url string) *ScheduledFlight {
res := FetchResponse(url)
body := ResponseBodyToByte(res)
UnmarshalBodyToPointerFlight(body, &data)
return &data
}
func UnmarshalFlightStatsURL() []string {
urlList := listOfURL()
var flightsToSunnyCities []string
for _, item := range urlList {
var flightStats *ScheduledFlight = GetFlightData(item)
var thisNumber string = flightStats.FlightNumber
flightsToSunnyCities = append(flightsToSunnyCities, thisNumber)
}
fmt.Println(flightsToSunnyCities)
return flightsToSunnyCities
}
The structs that I'm using are shown here:
type Welcome struct {
ScheduledFlights []ScheduledFlight `json:"scheduledFlights"`
}
type ScheduledFlight struct {
CarrierFSCode string `json:"carrierFsCode"`
FlightNumber string `json:"flightNumber"`
DepartureAirportFSCode string `json:"departureAirportFsCode"`
ArrivalAirportFSCode string `json:"arrivalAirportFsCode"`
}
I suspect this issue is arising from ScheduledFlights being of type []ScheduledFlight which would need to be accounted for, however I'm at a loss at what a solution would be. If anyone has any advice it would be much appreciated, thanks.