Getting a list of dictionaries from a sensor

Hi there,
I have a sensor, which holds a list of dictionaries. But I'm struggling to get acces to the items.
If I set a list from the sensor I get a list of the characters.
If I set the list with the very same string copied from the output, I get a list of dictionaries as expected.
Hopefully somebody has an idea, what I'm doing wrong.

Input to template editor in development tools:

{% set list = states('sensor.pet_feeder_c1_schedule')%}
{{list}}
list[0]: {{list[0]}}
list[1]: {{list[1]}}
list[2]: {{list[2]}}
----------------------------------------------
{% set list = [{'days': 'everyday', 'hour': 2, 'minute': 0, 'size': 2}, {'days': 'everyday', 'hour': 6, 'minute': 0, 'size': 3}, {'days': 'everyday', 'hour': 16, 'minute': 0, 'size': 3}]%}
{{list}}
list[0]: {{list[0]}}
days: {{list[0].days}}
hour: {{list[0].hour}}

And here is the output:

[{'days': 'everyday', 'hour': 2, 'minute': 0, 'size': 2}, {'days': 'everyday', 'hour': 6, 'minute': 0, 'size': 3}, {'days': 'everyday', 'hour': 16, 'minute': 0, 'size': 3}]
list[0]: [
list[1]: {
list[2]: '
----------------------------------------------

[{'days': 'everyday', 'hour': 2, 'minute': 0, 'size': 2}, {'days': 'everyday', 'hour': 6, 'minute': 0, 'size': 3}, {'days': 'everyday', 'hour': 16, 'minute': 0, 'size': 3}]
list[0]: {'days': 'everyday', 'hour': 2, 'minute': 0, 'size': 2}
days: everyday
hour: 2

Any idea would be apprecheated
Thanks, Pauli

This is because the state of an entity like a sensor is always a string. You can convert it to a dictionary using from_json (the template editor does this by itself, which is confusing).

{% set list = states('sensor.pet_feeder_c1_schedule')|from_json %}

from_json doesn't like single quotes, so you may need to replace them with double quotes first

{% set list = states('sensor.pet_feeder_c1_schedule').replace("'",'"')|from_json %}
1 Like

Thanks a lot slimak,
That did the trick!
I tried from_json before, but without replacing the single quotes.

Just FYI, states are limited to 255 characters and will be truncated if they exceed the limit, which may cause from_json to fail if the truncated value isn't a valid json string. You may be better served moving the list into a attribute.

1 Like