Jinja in Command Line Sensor: Count as value, list as attribute

I need to get all devices from my ZigBee coordinator in a certain state. I want

  • those devices as attribute for the command line sensor
  • the number of all devices as value vor the command line sensor

Update

Update to shorten things up: is there a smarter way to get the total number instead of passing almost the same command for a 2nd time (not very efficient hammering the API)?
I decided as quick and dirty approach to simply mixing “list” and “count” in one command:

Current result

  - platform: command_line
    name: Aqara-Devices Missing Status-Updates
    unique_id: xyz
    command_timeout: 60
    command: 'curl -s http://192.168.1.1/api/ABC/sensors | jq -r "{ "devices": [ .[] | select(.manufacturername==\"LUMI\") | select(.lastseen < \"$(date -u -d@$(($(date +%s)-360)) +%Y-%m-%dT%H:%M:%S)\")] | map(.name) | sort | unique, "total": [ .[] | select(.manufacturername==\"LUMI\") | select(.lastseen < \"$(date -u -d@$(($(date +%s)-360)) +%Y-%m-%dT%H:%M:%S)\")] | map(.name) | sort | unique | length }"'
    value_template: "{{ value_json.total }}"
    json_attributes:
      - devices

Old stuff below

Devices achieved with:
curl -s http://192.168.1.1/api/ABC/sensors | jq -r "[ .[] | select(.manufacturername==\"LUMI\") | select(.lastseen < \"$(date -u -d@$(($(date +%s)-366)) +%Y-%m-%dT%H:%M:%S)\")] | map(.name) | sort | unique | join(\", \") "

…which gives e. g.:
Type Name 1, Type Name 2, Type Name 3

Counting those is done with
curl -s http://192.168.1.1/api/ABC/sensors | jq -r "[ .[] | select(.manufacturername==\"LUMI\") | select(.lastseen < \"$(date -u -d@$(($(date +%s)-366)) +%Y-%m-%dT%H:%M:%S)\")] | map(.name) | sort | unique | length "
which gives 3 in this example.


How to get both?

  • count as value
  • list as attribute

I managed to get the command output as attribute using this:

  - platform: command_line
    name: Aqara-Devices Missing Status-Updates
    unique_id: xyz
    command_timeout: 60
    command: 'curl -s http://192.168.1.1/api/ABC/sensors | jq -r "{ "devices": [ .[] | select(.manufacturername==\"LUMI\") | select(.lastseen < \"$(date -u -d@$(($(date +%s)-360)) +%Y-%m-%dT%H:%M:%S)\")] | map(.name) | sort | unique }"'
    value_template: "{{ value_json.devices | length }}"
    json_attributes:
      - devices

command itself returns this:

{
  "devices": [
    "Type Name 1",
    "Type Name 2",
    "Type Name 3"
  ]
}

Unfortunately counting is not working (currently giving 0 as sensor value).

This is really freaking me out as I’m simply unable to access the elements of “devices” to do a simple count (or length) in the value_template.