glance
glance copied to clipboard
Custom API Array Filter
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?
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 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>