Andreas Hartmann
Andreas Hartmann

Reputation: 1883

Extract the highest value from a json array using a shell script

Using jq, I extracted a json array from a data source that looks something like this:

[
  {
    "rank": 69,
    "name": "Luigi"
  },
  {
    "rank": 420,
    "name": "Peach"
  },
  {
    "rank": 666,
    "name": "Toad"
  },
  {
    "rank": 42,
    "name": "Mario"
  }
]

Is there an elegant way of extracting the highest value of a field in the array within a shell script? In this example, I'm trying to get "666". I could write a dedicated program to do this easily, but I'd prefer to stay in a single shell script, unless it's too ugly to do that. I'm in the context of an Ubuntu Docker container and can install additional packages if needed.

Upvotes: 0

Views: 479

Answers (2)

Maks Babarowski
Maks Babarowski

Reputation: 672

With jq, you can use max_by function:

max_by(.rank) will yield:

{
  "rank": 666,
  "name": "Toad"
}

The result can be then piped to extract rank from it: max_by(.rank)|.rank (gives 666). Run this query from terminal by prepending it with jqjq 'max_by(.rank)|.rank'.

Upvotes: 5

dg428
dg428

Reputation: 441

Assuming the json is in a file called data.json :

cat data.json | jq .[].rank | sort -n -r | head -n 1

Upvotes: 1

Related Questions