Closed maforshaw closed 1 year ago
You can actually do this already via templates (also works with the built-in sensor/binary_sensor templates).
Example:
var:
my_var:
friendly_name: Var with Attributes as Object and Array
initial_value: 100
attributes:
my_object: >-
{{ {
'aaaa': 'value_aaaa',
'bbbb': 'value_bbbb',
'cccc': 'value_cccc'
} }}
my_array: >-
{{ [
'item1',
'item2',
'item3'
] }}
You can then access the values as normal:
{{ states.var.my_var.attributes.my_object }}
Returns: {'aaaa': 'value_aaaa', 'bbbb': 'value_bbbb', 'cccc': 'value_cccc'}
{{ states.var.my_var.attributes.my_object.aaaa }}
Returns: value_aaaa
{{ states.var.my_var.attributes.my_array }}
Returns: ['item1','item2','item3']
{{ states.var.my_var.attributes.my_array[0] }}
Returns: item1
Perfect, thank you @jb1228
It would be nice if var attributes could be optionally stored as objects instead of strings. For example, I use a var SQL query to return multiple records as a JSON array which is then stored in an attribute.
To then use this attribute later I need to deserialise every time with "from_json" which is not ideal.
I know this is possible because I was previously using the component ha-sql_json which says this:
To overcome this, if you look at the source code, it works out the object type as follows:
This means a JSON string that is output from the SQL query is then stored in the attribute as a list (or dictionary, depending on content) with no need to deserialise later.
To maintain backwards compatibility, I guess you could either add a boolean property whether to automatically work it out as above or a property to specify the data type.