Rules and Expressions with Open Weather API

Hi @Jason_K_Jennings and @dave.blackwell - I hope you don’t mind that I moved your posts out of the Open Weather Custom Tile thread and into this Open Weather Rule thread. Great discussion above!

If the ‘alerts’ field exists, but it might be an empty array, you could do something like the following:

weather = $context.response.data
count(weather.alerts) > 0

If you’re not sure if the field will exist or not, you could either:

  • Initialize an expression scoped variable with an empty array if the alerts doesn’t exist
  • Conditionally evaluate the count or not

Initialize Array

weather = $context.response.data
alerts = isEmpty(weather.alerts) ? [] : weather.alerts
count(alerts) > 0

In the second line, we’re using isEmpty() which can check for an empty string, empty array, or in this case a missing property (eg. undefined). And even if the property did exist and was empty, this doesn’t hurt as it’s still just using an empty array in that case. And if it does exist and does have content, it uses the content.

Conditionally Count

weather = $context.response.data
isEmpty(weather.alerts) ? false : count(weather.alerts) > 0

Same concept as above with using isEmpty(). This ones a bit shorter, but I personally find the logic of the other one easier to interpret… which is important when I try to edit an expression a few months later and need to remember what the heck I did!

1 Like