I am having a problem with errors in my log caused by a template sensor when the value_template
has no value. I know the normal way to avoid this but I might have found a flaw in HA where this is not possible to do (or more likely of course, I don’t know how to do it!)
Please read on if this is your area of expertise and don’t be put off by the length of this post, most of it is just for illustrative purposes
I use a sensor platform (UK Transport but don’t stop reading if you don’t use it) that returns nested JSON about future trains.
- platform: uk_transport
app_id: !secret uk_transport_app_id
app_key: !secret uk_transport_api
queries:
- mode: train
origin: LIV
destination: WAT
scan_interval: 86400
And here is the JSON
{
"station_code": "LIV",
"calling_at": "WAT",
"next_trains": [
{
"origin_name": "Liverpool Street",
"destination_name": "Watford",
"status": "ON TIME",
"scheduled": "09:26",
"estimated": "09:26",
"platform": "4",
"operator_name": "TfL Rail"
},
{
"origin_name": "Liverpool Street",
"destination_name": "Watford",
"status": "ON TIME",
"scheduled": "11:12",
"estimated": "11:12",
"platform": "4",
"operator_name": "TfL Rail"
}
],
"unit_of_measurement": "min",
"friendly_name": "Next train to WAT",
"icon": "mdi:train"
}
The docs suggest templating like this:
value_template: '{{ states.sensor.next_train_to_wat.attributes.next_trains[x].scheduled }}'
which works (obviously) but as you would expect it throws an error if there is no next_trains[x]
.
I experimented with various alternatives:
value_template: '{{ value_json.next_trains[x].scheduled }}
which also works but still throws an error if next_trains[x]
doesn’t exist. (also it’s a bugger to test as I can’t see a way to do it in the template tool!)
Is there a way to template this sensor without it throwing an error if the next_trains[x]
doesn’t exist. For example, I tried:
value_template: '{{ state_attr('sensor.next_train_to_wat', 'next_trains[x].scheduled' }}'
which doesn’t work, and nor does
value_template: '{{ state_attr('sensor.next_train_to_wat', 'next_trains[x]', 'scheduled' }}'`