23w4ertfgyhj
23w4ertfgyhj

Reputation: 703

Get json object that has latest timestamp using jq

I have a below json file but I'm struggling to only display the description with the latest createdDate.

I tried with

>
<
todateiso8601?
now

and a few more but I can't get this to work.

Would anyone be able to help?

JSON:

{
    "items": [
        {
            "createdDate": 1543585940, 
            "id": "awefef", 
            "description": "this is description 1"
        }, 
        {
            "createdDate": 1555324487, 
            "id": "hjkvhuk", 
            "description": "this is description 2"
        }, 
        {
            "createdDate": 1547034297, 
            "id": "xdfxdfv", 
            "description": "this is description 3"
        }
]
}

Upvotes: 2

Views: 4808

Answers (2)

peak
peak

Reputation: 116770

Simply sort by .createdDate and (assuming you only want one value even if there is more than one with the greatest .createdDate value), select the last one:

.items
| sort_by(.createdDate)[-1].description

Ties

If you want all the descriptions in the case of ties:

.items
| sort_by(.createdDate)
| (.[-1].createdDate) as $max
| .[]
| select($max == .createdDate)
| .description

Upvotes: 3

Goldfish
Goldfish

Reputation: 720

EDIT: use peaks answer it is superior

Here is a simple script that does this in 2 commands. Probably can be done in 1 but alas my nooblet skills were not enough

You can pipe to max with an array of numbers in JQ and it will return the largest value in the input array.

Then we use select to grab the object containing the max value and output the description.

We will also use arg which allows us to reference a local environment variable, and we need to cast it to a number or JQ thinks it's a string.

maxDate=$(cat tmp.json | jq '[.items[].createdDate] | max')

cat tmp.json | jq --arg maxDate "$maxDate" '.[][] | select(.createdDate == ($maxDate | tonumber)).description'

Output:

"this is description 2"

In the future, please post your desired output as well as your question so responders can be confident they are solving the problem to your liking

Upvotes: 1

Related Questions