jonesi100
jonesi100

Reputation: 11

Using jq group_by and count to sort JSON output from curl into sorted and counted list

Can anyone help me to understand and assist with a jq script please (only using jq)? Can anyone help me to write a script to take the output of:

`curl --silent "https://api.surfshark.com/v3/server/clusters" | jq` 

and list the number of servers in each countryCode and the min and max loadings on those servers, sorted by countryCode?

.countryCode 'count of number of servers' 'lowest .load' 'highest .load'
AU    5    13%       30%
UK   10    35%       88%
US   25    12%       50%

etc....

I believe the use of group_by, or a combination of that and map, set path, get path and count may work, but I'm hoping someone with higher skills can help me.

Each json entry looks like this:


[
  {
    "country": "Albania",
    "**countryCode**": "AL",
    "region": "Europe",
    "regionCode": "EU",
    "**load**": 12,
    "id": "4c333aa2-d08b-4d11-9073-61c351ce1c1e",
    "coordinates": {
      "longitude": 19.8188889,
      "latitude": 41.3275
    },
    "info": [
      {
        "id": "55994450-0c87-4df3-b585-3836c67a863d",
        "entry": {
          "value": "U2FsdGVkX1/VX5IKc3H3ruClgbw7JgnqW7Eacumx8aM="
        }
      }
    ],
    "type": "generic",
    "location": "Tirana",
    "**connectionName**": "al-tia.prod.surfshark.com",

Extract from another post referencing some of the possible commands

'map(.Properties.ItmId)
| reduce .[] as $i (
    {}; setpath([$i]; getpath([$i]) + 1)
  )
| to_entries | .[] | { "ItemId": .key, "Count": .value }'

Upvotes: 1

Views: 712

Answers (1)

shyam
shyam

Reputation: 9368

You could do the group_by first and then derive the rest of the fields from there

group_by(.countryCode) 
  | map([ .[0].countryCode, length, min_by(.load).load, max_by(.load).load])

EDIT: Removed the redundant sort as pointed out by @peak

You could optionally add .[] | @tsv to get the table structure that you have in the question

Upvotes: 1

Related Questions