I have the below JSON from the curl output and I need to retrieve the number of host_name
(hosts) that has wkn
in its hostname. In the below json we have two hosts that has wkn
in their host_name
.
{
"href": "http://10.10.0.10:8080",
"Hosts": {
"cluster_name": "test",
"host_name": "testmasternode.example.test.com",
"ip": "10.10.0.10"
}
}
{
"href": "http://10.10.0.10:8080",
"Hosts": {
"cluster_name": "test",
"host_name": "testwkn01.example.test.com",
"ip": "10.10.0.11"
}
}
{
"href": "http://10.10.0.10:8080",
"Hosts": {
"cluster_name": "test",
"host_name": "testwkn02.example.test.com",
"ip": "10.10.0.12"
}
}
I tried a couple of ways
- This doesn't give any output
curl -sH http://10.10.0.10:8080/api/v1/clusters/test/hosts?fields=Hosts/host_name,Hosts/ip | jq -r '.items | .[] | select(.Hosts.host_name == ("*wkn01.*"))'
- This gives an error
curl -sH http://10.10.0.10:8080/api/v1/clusters/test/hosts?fields=Hosts/host_name,Hosts/ip | jq -r '.items | .[] | select(.Hosts.host_name | match("*wkn01.*"))'
jq: error (at <stdin>:76): Regex failure: target of repeat operator is not specified
CodePudding user response:
Use test
instead of match
as you only need a boolean result. Then, to test if any item "has wkn
in their host_name
" the regex wkn
should suffice. Lastly, as you "need to retrieve the number of host_name
", simply finalize with length
(which needs an array, therefore I also changed .[]
to map
).
... | jq -r '.items | map(select(.Hosts.host_name | test("wkn"))) | length'
2