JSON output in my template sensor

Hi there!

I am using a rest sensor to retrieve JSON output from a remote instance. I’m interested in the values of electricity1 and electricity2.

Initially I thought I had a list of attributes, so I tried to use the following in a template sensor:

   - platform: template
     sensors:
       sensor_dsrm:
         friendly_name: "Yesterdays power consumption"
         entity_id: sensor.lastday_consumption
         unit_of_measurement: 'kWh'
         value_template: "{{ state_attr('sensor.lastday_consumption', 'electricity1') | float + state_attr('sensor.lastday_consumption', 'electricity2') | float }}"

This is obviously not working, as electricity1 and electricity2 are not state attributes. How do I get the values in my template sensor?

It looks like you have to go through “results” first.

{{ state_attr('sensor.lastday_consumption', 'results').eletricity1 
  + state_attr('sensor.lastday_consumption', 'results').eletricity2 }}

Not used to looking at states in that format, but it looks like the results attribute actually contains a list. Also the values of electricity1 and electricity2 look like string representations of floats. So maybe:

value_template: >
  {% set d = state_attr('sensor.lastday_consumption', 'results')[0] %}
  {{ d.electricity1|float + d.electricity2|float }}
1 Like

Looking at that again, I think you’re right.

New feature in Home Assistant that makes YAML the consistent way to specify options throughout the product.

Ironically, it makes it more challenging (for me) to identify data structures for developing templates. In comparison to JSON, my eyes can’t (yet) quickly discern lists and dictionaries when expressed as YAML.

This:

results:
  - id: 123
    a: 'cat'
    b: 'bat'
    c: '456'
  - id: 789
    a: 'flat'
    b: 'round'
    c: '000'

is this:

{
  "results": [
    {
      "id": 123,
      "a": "cat",
      "b": "bat",
      "c": "456"
    },
    {
      "id": 789,
      "a": "flat",
      "b": "round",
      "c": "000"
    }
  ]
}

This worked for me! Excellent! Thanks both of you guys, appreciate it.

1 Like