Value_template causing errors in log

This sensor gives an error when there is no train

  next_train_status:
    friendly_name: 'Next train status'
    entity_id: sensor.next_train_to_abc
    value_template: '{{states.sensor.next_train_to_abc.attributes.next_trains[0].status}}'

but I can’t work out what the correct way to format it is to prevent it. This doesn’t seem to work

value_template: {{ state_attr('sensor.next_train_to_abc', 'next_trains[0].status') }}

Try that. I use similar for NSW Transport

        value_template: >-
          {% if is_state_attr('sensor.karionggosford', 'due', 'n/a') %}
            No schedule found
          {% else %}
            {{ states.sensor.karionggosford.attributes.route }} in {{ states.sensor.karionggosford.attributes.due }}m ({{ states.sensor.karionggosford.attributes.delay }}m delay)
          {% endif %}

Just added mine… I think my first suggestion isn’t right. The template editor in dev-tools works like mad in troubleshooting this stuff. If you go into states you will see all the key names for the sensor and then you can work it out from that normally.

Unfortunately that doesn’t work (UK Transport sensor)

EDIT just seen your update, will check tomorrow. Thanks.

yeah just check my edit above…
image

No that doesn’t work for UK Transport.

The sensor returns some nested JSON and the only way I can find to read it is the way I am doing it now (as documented in the docs for the component) or by this

value_template: '{{ value_json.next_trains[1].scheduled}}'

which 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!)

In my opinion this is a flaw in HA to not be able pre-empt this error. I think I’ll probably start a new thread. Maybe there is a way that I don’t know about?