Creating valid JSON output from jinja template

Try this version in the Template Editor.

{% set devices = state_attr('sensor.all_network_devices', 'devices') %}
{% set ns = namespace(devices=[]) %}
{% for d in devices %}
  {% set ns.devices = ns.devices + [dict(
    order=d.ip[0].split('.')[3], 
    mac=d.mac,
    ip=d.ip[0],
    state=d.state,
    name=d.name,
    type=d.type,
    first_seen=d.first_seen,
    last_changed=d.last_changed)] %}
{% endfor %}
{{ ns.devices }}

I tested it (using other data) and it produces a valid list of dictionary items.

Feel free to add/modify the dictionary keys to meet your requirements.

2 Likes