REST sensor works but not for zero?

I’ve written a rest sensor which reads a URL which returns a simple integer:

- platform: rest
  name: sip_days_since_last_run
  value_template: '{% if value_json %}{{ value_json }}{% endif %}'
  scan_interval: 600

The sensor works fine except for zeros, which it turns into blank - no value.

As I’m writing this post I think I get it - the if value_json is evaluating to false for zero values so the sensor simply has no value.

I want it to treat zeros as a legitimate value, but not update if the page is for some reason unreachable or blank. Is there a smarter replacement for the if as written here?

Well, you’re not parsing the JSON at all, so is the result always an integer? If so, remove the if statement altogether and just return {{ value }}.

if 0 in Jinja/Python evaluates to False.

1 Like

Thanks. I’m not sure this is exactly what I was hoping for, as I think it will update the sensor value if the page is unreachable, but it’s more correct than what I’ve done so far so I’ll mark this as the solution.

So you want to handle the case where there’s an API error or timeout and specify a value for that in your sensor? You can use if value is defined....

{{ value_json }} is all you need.

This topic was solved already. value_json only works if the response can actually be parsed as JSON. The data from this API doesn’t return JSON.

Did you deliberately ignore the forum notification when posting that the topic was solved?

Sorry. I missed it.