I’m having a lot of trouble doing something that I’m sure is really simple.
I have read numerous posts and guides to this, but I’m getting either errors or all the data at once in one attribute.
Most other posts are about setting the sensor value from one record, by selecting the wanted value name.
After a week of messing around, I give up and come here for help.
json:
{
"total": 13,
"records": [
{
"Hour": "2022-11-22T11:00:00",
"Price": 1666.890015
},
{
"Hour": "2022-11-22T12:00:00",
"Price": 1583.589966
},
Ideally I would create a sensor with attributes for every record, with the attribute name being the index [0-number of records] or name being the value of Hour
, and the value being Price
.
I can create a sensor with the state being Price
of the first record:
resource: https://api.xxxx
name: price_now
value_template: "{{ value_json.records[0]['Price'] | round(2) | float / 1000 }}"
But I need to extract the Price
from every record (in this case 13, but it varies) and store it somehow, for use in automations.
Of course I could create a long list of sensors, with state being the value of Price
, but that seems less elegant and requires too many resource requests so I would get blocked.
- platform: rest
scan_interval: 3600
resource: https://api.xxxxx.xx
name: price_future
value_template: "OK"
# json_attributes:
# - Hour
# - Price
- platform: template
sensors:
price_1:
value_template: "{{ value_json.records[0]['Price'] | round(2) | float / 1000 }}"
price_2:
value_template: "{{ value_json.records[1]['Price'] | round(2) | float / 1000 }}"
gives me nothing.
value_template: >
{% for x in range(value_json.records|count) %}
{{ value_json["records"][x]["Price"] }}
{% endfor %}
also nothing…
json_attributes:
- price_future
{% for x in range(value_json.records|count) %}
{{ state_attr('sensor.price_future[x]', 'Price') }}
{% endfor %}
I think attributes must be declared before, so this will also not work.