Formatting a generic sensor template output into a list

I have a sensor “template” that lists the information of all the entities that concern the batteries.

- platform: template
  sensors:
    batteries:
      friendly_name: Batteries info
      value_template: >
       {{ this.attributes.lst |count}}
      attribute_templates:
        lst: >
         {{ states.sensor
            | selectattr('attributes.device_class', 'eq', 'battery')
            | sort(attribute='entity_id')  }}

The “lst” attribute gives me this output:

[<template TemplateState(<state sensor.albina_smartphone_oneplus_nord_ce_2_lite_5g_battery_level_2=100; unit_of_measurement=%, device_class=battery, icon=mdi:battery, friendly_name=Albina smartphone OnePlus Nord CE 2 Lite 5G Battery level @ 2024-07-06T16:03:59.782607+02:00>)>, <template TemplateState(<state sensor.alex_smartphone_oneplus_nord_ce_2_lite_5g_battery_level=93; unit_of_measurement=%, device_class=battery, icon=mdi:battery-90, friendly_name=Alex smartphone OnePlus Nord CE 2 Lite 5G Battery level @ 2024-07-06T17:23:43.353748+02:00>)>]

I would instead need a decent output in list format like in this example:

[
  {
    "entity_id": "sensor.alex-cell",
    "state": "75",
    "unit_of_measurement": "%",
    "device_class":"battery",
    "icon":"mdi:battery",
    "friendly_name":"alex-cell"
  },
  {
    "entity_id": "sensor.mom-cell",
    "state": "100",
    "unit_of_measurement": "%",
    "device_class":"battery",
    "icon":"mdi:battery",
    "friendly_name":"sensor.mom-cell"
  }
]

I’m not good with formatting, please help me. Thanks in advance

To retrieve only a limited set of data points from the state objects of the entities you will need to use a namespace and for loop to build the list you want:

{% set ns = namespace(short=[]) %}
{% for obj in states.sensor
| selectattr('attributes.device_class', 'defined')
| selectattr('attributes.device_class', 'eq', 'battery') 
| sort(attribute='entity_id') %}
{% set ns.short = ns.short + [{
  'entity_id': obj.entity_id,
  'state': obj.state,
  'unit_of_measurement': obj.attributes.unit_of_measurement,
  'device_class': 'battery',
  'icon': obj.attributes.icon,
  'friendly_name': obj.name  }] %}
{% endfor %}
{{ ns.short}}

Keep in mind that an attribute built like this is effectively doubling a bunch of data that is already available and will update often, contributing to database bloat…

Someone here on the forum can likely help with more efficient and effective method if you describe your goal and needs.

What is the intended application for a list of battery data?