Template sensor with values from list?

Hi

I have a sensor where the state is returned as a list.

{{ states('sensor.graes_prognose') }}

[
{
“date”: “2024-05-14”,
“value”: “1”
},
{
“date”: “2024-05-15”,
“value”: “1”
},
{
“date”: “2024-05-16”,
“value”: “1”
},
{
“date”: “2024-05-17”,
“value”: “1”
},
{
“date”: “2024-05-18”,
“value”: “1”
}
]

I would like to make a template sensor where the five values are stored as attributes called Day 1, Day 2, Day 3 and so on.

I’m thinking that I have to isolate the values somehow. I can get this far and then I run out of programming skills. :slightly_smiling_face:

{{ states('sensor.graes_prognose').split(',')[1] }}

‘value’: ‘1’}

Can somehow help me the last bit of the way, or maybe there is a smarter way of accomplishing this?

If you want an attribute for day 1 you could just add an attribute to your template sensor and give a value of:

states('sensor.graes_prognose')[0]['value']

I would personally do some failsafe checking first to make sure it’s a list and that element 0 exists but otherwise, that’s the code.

1 Like

For Day 1 sensor:

{% set json_obj = states('sensor.graes_prognose') | from_json %}
{{ json_obj[0].value }}
1 Like

If I test this in the template editor, I get the following:

‘str object’ has no attribute ‘value’

I’m not 100% sure if I should be able to test this by just typing it into the template editor, but when I do, I get the following:

JSONDecodeError: unexpected character: line 1 column 3 (char 2)

Does your sensor state really have the curly quotes ( and instead of ") that you pasted above? If so, from_json won’t work correctly.

This is what I have in the template dev tool page that works (pasting your sensor state into a string, since I don’t have such a sensor):

{% set str = '[
{
“date”: “2024-05-14”,
“value”: “1”
},
{
“date”: “2024-05-15”,
“value”: “1”
},
{
“date”: “2024-05-16”,
“value”: “1”
},
{
“date”: “2024-05-17”,
“value”: “1”
},
{
“date”: “2024-05-18”,
“value”: “1”
}
]' %}

{% set json_obj = str | replace('“','"') | replace('”', '"') | from_json %}
{{ json_obj[0] }}
1 Like

Which integration produces that sensor?

2 Likes

Sorry, I used the block quote formatting by mistake.

The sensor state does not have curly quotes.

[
  {
    "date": "2024-05-14",
    "value": "1"
  },
  {
    "date": "2024-05-15",
    "value": "1"
  },
  {
    "date": "2024-05-16",
    "value": "1"
  },
  {
    "date": "2024-05-17",
    "value": "1"
  },
  {
    "date": "2024-05-18",
    "value": "1"
  }
]

It’s a REST sensor, so RESTful.

Currently, you are using the RESTful integration to create one sensor and trying to extract information out of its value to create 5 attributes.

I suggest you create five separate sensors.

rest:
  - resource: http://the_url_you_are_using
    sensor:
      - name: "Day 1"
        value_template: "{{ value_json[0].value }}"
      - name: "Day 2"
        value_template: "{{ value_json[1].value }}"
      - name: "Day 3"
        value_template: "{{ value_json[2].value }}"
      - name: "Day 4"
        value_template: "{{ value_json[3].value }}"
      - name: "Day 5"
        value_template: "{{ value_json[4].value }}"

RESTful - Home Assistant (home-assistant.io)


EDIT

Let me know if you also need the date field.

2 Likes

Maybe I should clarify.

I’m using a piece of code that uses the REST integration to create a sensor from a specific resource.
The code is not something I have written myself and I don’t have the skills to adapt it to my needs.
It’s several lines of code.

The sensor it creates has a state that is one long string which contains five sets of information. It is from this string I would like to extract the “value” portion, which at the time of writing is the number 1 for all five.

[
  {
    "date": "2024-05-14",
    "value": "1"
  },
  {
    "date": "2024-05-15",
    "value": "1"
  },
  {
    "date": "2024-05-16",
    "value": "1"
  },
  {
    "date": "2024-05-17",
    "value": "1"
  },
  {
    "date": "2024-05-18",
    "value": "1"
  }
]

It’s not that important if it ends up being one sensor with five attributes or five separate sensors, although I would prefer one sensor with five attributes.

There are two integrations that employ REST to create sensors and both simply require a few lines of YAML to define a sensor.

  1. RESTful Sensor - Home Assistant (home-assistant.io)

  2. RESTful - Home Assistant (home-assistant.io)

What is this “piece of code” you are referring to because it doesn’t sound like it employs either of the two REST integrations I mentioned. If it does use one of the two aforementioned integrations, please post the “several lines of code”.

1 Like

Here is the code for the REST sensor.

rest:
  scan_interval: 3600
  resource: https://www.astma-allergi.dk/umbraco/Api/PollenApi/GetPollenFeed
  sensor:
    - name: "Græs (prognose)"
      icon: mdi:grass
      value_template: >
        {% set region = '48' %}
        {% set pollen = '28' %}
        {% set prognose = (value_json | from_json).fields[region].mapValue.fields.data.mapValue.fields[pollen].mapValue.fields.predictions.mapValue.fields %}
        {% set data = namespace(predictions=[]) %}
        {% for p in prognose %}
        {% set data.predictions = data.predictions + [{'date': p[6:10]+p[2:5]+'-'+p[:2], 'value': prognose[p].mapValue.fields.prediction.stringValue}] %}
        {% endfor %}
        {{ data.predictions |  sort(attribute="date")}}

It’s a sensor that collects Danish pollen figures.
“Græs” means grass. “Prognose” means prediction.
Region = 48 is for the western part of Denmark (east is 49).
Pollen = 28 defines the type of pollen (grass in this example).

There are several other sensors for other pollen types, but for the sake of simplicity I just pasted the code for one single type.

I just noticed something.
When using this code:

{% set str = '[
  {
    "date": "2024-05-14",
    "value": "1"
  },
  {
    "date": "2024-05-15",
    "value": "1"
  },
  {
    "date": "2024-05-16",
    "value": "1"
  },
  {
    "date": "2024-05-17",
    "value": "1"
  },
  {
    "date": "2024-05-18",
    "value": "1"
  }
]' %}

{% set json_obj = str | from_json %}
{{ json_obj[0].value }}

I get the expected result:

1

So I’m a little stumped why this doesn’t work.

{% set json_obj = states('sensor.graes_prognose') | from_json %}
{{ json_obj[0].value }}

JSONDecodeError: unexpected character: line 1 column 3 (char 2)

Thanks for posting it. Now I understand that the “piece of code” is simply the configuration of a REST sensor.

I added it to my system so that I could view the data it produces. Its template selects and reformats a portion of the received data (because the received data doesn’t guarantee the dates are in ascending order and they’re presented in a non-ISO format).

I get the same error message.

Here’s all you need to do to eliminate it:

{% set json_obj = states('sensor.graes_prognose') | replace("'", '"') | from_json %}
{{ json_obj[0].value }}

Now you have the means to create separate Template Sensors for Day 1, Day 2, etc. Alternately, you can create a single Trigger-based Template Sensor that reports each day as a separate attribute. If you intend to track/graph the history of each day’s value then you will need to record them as separate Template Sensors (not as attributes of a single sensor).

1 Like

Fantastic. Thank you and everyone else for your help.

I really appreciate it.

1 Like

When it comes to this kind of thing you got one of the best guys on the job, @123 is one of the best folks to help on HA. I’ve enjoyed seeing his solution!

2 Likes