glance icon indicating copy to clipboard operation
glance copied to clipboard

Custom API Array Filter

Open ralphocdol opened this issue 8 months ago • 1 comments

Description

This is mostly to use with length, I'd imagine something like this:

{{ len (.JSON.ArrayFilter "student" (ge "age" 20)) }}

I did ask something similar before but not officially. Is there a way around this currently?

ralphocdol avatar Mar 18 '25 01:03 ralphocdol

Assuming your response looks like this:

{
  "students": [
    {
      "age": 20,
      "name": "Alice"
    },
    {
      "age": 30,
      "name": "Bob"
    },
    {
      "age": 40,
      "name": "Charlie"
    }
  ]
}

You can use the following:

{{ len (.JSON.Array "students.#(age>20)#") }}

Have a look at tidwall/gjson's docs for all of the other ways in which you can filter the data. It's an amazingly awesome library.

svilenmarkov avatar Mar 18 '25 12:03 svilenmarkov

@svilenmarkov Thanks for this, managed to make it work, there's a bit of learning curve though. Here's an example for those who might need to use it. My example is for a Proxmox widget at API endpoint /api2/json/cluster/resources.

<div>
  {{ $lxc_running := len (.JSON.Array "data.#(type==\"lxc\")#|#(status==\"running\")#|#(template==0)#") }}
  {{ $lxc_total := len (.JSON.Array "data.#(type==\"lxc\")#|#(template==0)#") }}
  <div class="color-highlight size-h3">{{ $lxc_running }}/{{ $lxc_total }}</div>
  <div class="size-h5 uppercase">LXC</div>
</div>

ralphocdol avatar Mar 19 '25 12:03 ralphocdol