WTH does from_json not offer fallback values for invalid json?

I would like there to be an easy way to offer a default/fallback value when using templates and from_json struggles with invalid json.

Example:

I have a rest sensor that returns an array of integers as well as a script that returns a random integer from said array.

{{ states('sensor.rest_list_of_integers') 
     | from_json() 
     | random() }}

If the sensor for any reason would give me something else than an array I would be fine if the template just resolved to the integer 0. However, either way I’ve tried, as soon as the sensor has invalid JSON, it will instead log a “JSONDecodeError”… I can’t figure out if there’s any way for the template to swallow that and give me a default value instead?

Are these special integers?

Why not just use the range() function with random()?

e.g. {{ range(42,101)|random }}

Or use this integration https://www.home-assistant.io/integrations/random/ ?

Yeah, unfortunately they are special integers.

Come to think about it, if I move the template that takes the random value to the Rest sensor config then I should be able to use a default value in the script when the sensor is undefined (which I assumes it is for invalid json)… I’ll give that a try!

The other option is to test your state value first:

{% if has_value('sensor.rest_list_of_integers') %}
  {{ states('sensor.rest_list_of_integers') 
       | from_json() 
       | random() }}
{% else %}
 42 {# replace with your default #}
{% endif %}

There may be better tests depending on the invalid json returned.