Hi
I am after some advice please in the best way to handle a JSON unmarshal issue I have for a hobby project.
I have been successfully using the Nim JSON unmarshal proc to() in my program to extract the elements I want to use from a JSON API output - which happens to be for weather forecast data. Yesterday I added some code to also extract any weather alerts from the JSON data. This worked fine too - as we had some local thunderstorm warnings at that time.
Today there are no weather alters, so when I run when my program, the JSON unmarshal proc has no 'alerts' key to extract into my weather struct (object?) and consequently is throwing an exception for the missing '.alters' key. When present, this key is normally a sequence, but only when included in the forecast data.
I have added a try and except handler to catch this, which works ok. However, even with the exception being caught, the unmarshal proc is now also returning a nil for the whole unmarshal weather struct (object?) - even though all the other data exists still - just the 'alerts' are missing... I assumed once I caught this missing key exception, the remaining unaffected data would still be unmarshaled successfully as before. This is not the case - I just get nothing (nil) instead.
I am unsure on the best way to manage this, my ideas are:
Hopefully there is a way to handle this when using the unmarshal proc to() - I just have not found it yet on the docs pages.
The specific block of code (if it help to see what I have coded) is here: https://github.com/wiremoons/weather-nim/blob/master/src/getdata.nim from line 118.
Thanks for any help.
If "alerts" might not exist, you need to wrap it in Option (see options module in stdlib) like
WeatherForecast = ref object
latitude: float64
longitude: float64
timezone: string
currently: Currently
daily: Daily
alerts: Option[seq[Alerts]]
and then, after using json.to, check if it's present by myobj.alerts.isSome(), and if it is, get the value by myobj.alerts.get()
Thanks very much for the help Yardanico, and for the example code.
I was not aware of the option capability, which sounds like a great solution. I will give it a go in my program.
Thanks for for the tip on float vs float64 too :)