Extract nested attribute from sensor

Hi there,

I have a sensor from my heat pump with the very nested info about on_off_cycles which I’d like to extract in order to display them on my dashboard.

The sensor looks something like this:

// sensor.heat_pump_firmware_version

online_state: ONLINE
backup_heater_allowed_for: DISABLED
smart_photovoltaic_buffer_offset: 5
external_energy_management_activation: false
rts:
  statistics:
    - device_id: c0c9c0ab-729d-5b9d-94cc
      operation_time: 45183
      on_off_cycles: 541
    - device_id: 529e50e2-9f6a-59c9-ab87
      operation_time: 0
      on_off_cycles: 0
mpc:
  devices:
    - device_id: c0c9c0ab-729d-5b9d-94cc
      current_power: 842
    - device_id: 529e50e2-9f6a-59c9-ab87
      current_power: 3

I’d like to extract the on_off_cycles that returns “541” currently. Therefore I’ll somehow need to filter by device_id I’d assume.

Also, note that in the attribute “mpc” there are the same two device_ids present as well.

In the template editor

{{ state_attr('sensor.das_nymphengut_firmware_version', 'rts') }}

nicely prints out

{
  "statistics": [
    {
      "device_id": "c0c9c0ab-729d-5b9d-94cc-3456c6cefbe4",
      "operation_time": 45243,
      "on_off_cycles": 541
    },
    {
      "device_id": "529e50e2-9f6a-59c9-ab87-71efdde69895",
      "operation_time": 0,
      "on_off_cycles": 0
    }
  ]
}

I’ve tried something like

{{ state_attr('sensor.das_nymphengut_firmware_version', 'rts') | select('device_id','c0c9c0ab-729d-5b9d-94cc-3456c6cefbe4')}}

but it seems that “select” doesn’t work inside attributes !?

I’ve tried searching for similar problems, but so far I’ve not seen examples of such deep nesting.

Thanks!

{{ state_attr('sensor.heat_pump_firmware_version', 'rts')['statistics'] | first }}

returns

{
  "device_id": "c0c9c0ab-729d-5b9d-94cc",
  "operation_time": 45243,
  "on_off_cycles": 541
}

I’ll try to maybe save that in a variable and extract it from there …

{{ state_attr('sensor.das_nymphengut_firmware_version','rts')['statistics'][0]['on_off_cycles'] }}

Or if you wanted to explicitly specify the device rather than relying on it being first in your list:

{{ (state_attr('sensor.das_nymphengut_firmware_version','rts')['statistics']
    |selectattr('device_id','match','c0c9c0ab')|first)['on_off_cycles'] }}

Got it!

{{ state_attr('sensor.heat_pump_firmware_version', 'rts')['statistics'][0]['on_off_cycles'] }}

Thanks! :rofl:

Aweome, that’s even better! As I’m not sure whether it’s always the same order of devices.

Thanks so much! :slight_smile:

1 Like