Hello
I am reading MQTT records from a device but this MQTT record can have one or two strings of data like this:
{"gwIntervalDatas":[{"utcEndtime":1643956800000,"sensorId":4,"index0Delta":39,"index1Delta":0,"temperature":154,"humidity":88,"battLevel":100,"version":1}]}
{"gwIntervalDatas":[{"utcEndtime":1643957100000,"sensorId":4,"index0Delta":11,"index1Delta":0,"temperature":151,"humidity":88,"battLevel":100,"version":1},{"utcEndtime":1643957100000,"sensorId":5,"index0Delta":5,"index1Delta":0,"temperature":140,"humidity":100,"battLevel":100,"version":1}]}
To load some data from these input in Home Assistant, I am using sensors with the following code:
- platform: mqtt
state_topic: "servicelocation/8853e98f-b96e-4c14-8b60-32718b54f9f6/aggregatedGW"
name: "Smappee Sensor Index 1"
value_template: "{{ value_json.gwIntervalDatas[0].sensorId | int(default=0) }}"
- platform: mqtt
state_topic: "servicelocation/8853e98f-b96e-4c14-8b60-32718b54f9f6/aggregatedGW"
name: "Smappee Sensor Index 2"
value_template: "{{ value_json.gwIntervalDatas[1].sensorId | int(default=0) }}"
but I am getting the following error if there is only one string of data:
2022-02-04 08:40:01 ERROR (MainThread) [homeassistant.helpers.template] Template variable error: list object has no element 1 when rendering '{{ value_json.gwIntervalDatas[1].sensorId | int(default=0) }}'
I tried this but this is not working neither (same error):
- platform: mqtt
state_topic: "servicelocation/8853e98f-b96e-4c14-8b60-32718b54f9f6/aggregatedGW"
name: "Smappee Sensor Index 3"
value_template: >
{% if value_json.gwIntervalDatas[1].sensorId is defined %}
"{{ value_json.gwIntervalDatas[1].sensorId | int(default=0) }}"
{% else %}
{{ 6 }}
{% endif %}
How to avoid this āerrorā message ?
Thanks !