0

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.

2
  • 1
    grep -Eo '[[:digit:]]+' file.json | sort -n | tail -n1 Commented Jul 11, 2021 at 17:51
  • 2
    This works, but only if there are no other numeric values in the array. So it would work with my example but not the real data and the other answers are prettier. Thanks though! Commented Jul 11, 2021 at 17:54

2 Answers 2

5

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'.

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, just what I was looking for. Very clean, I should've read more about jq, didn't know these functions existed. Thanks!
Thanks for the edit. ;) ... now you have my upvote.
1

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

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

2 Comments

No need for the cat really.
Thanks, it works, but the other answer is more elegant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.