10

There is an array of json object, using jq how to check if an object exists if so returns the true else false

I tried this but getting error

cat fruits.json | jq '.fruits[]| sort_by(.version)'

I would like to sort by decending order and output the price of the most recent version.

{
    "fruits": [
        {
            "name": "banana",
            "color": "yellow",
            "price": 0.51,
           "version": 1
        },
        {
            "name": "banana",
            "color": "yellow",
            "price": 0.52,
            "version": 2
        }
    ]
}
2
  • Doyou mean to check whether version attribute exists ? Commented Dec 27, 2021 at 7:54
  • Something like cat fruits.json | jq '.fruits| sort_by(-.version) | first'? Or am I misunderstanding? Commented Dec 27, 2021 at 8:03

2 Answers 2

12

cat fruits.json | jq '.fruits | sort_by(-.version)[0].price'

produces:

0.52

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

1 Comment

Remove useless cat: jq '.fruits | sort_by(-.version)[0].price' fruits.json
7

You need try like:

.fruits |= sort_by(.version)

Example: https://jqplay.org/s/ntjioYhKWq

Reference sort by keys

Comments

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.