'jq - Get objects with latest date

Json looks like this:

cat test.json |jq -r ".nodes[].run_data"

  {   
    "id": "1234",   
    "status": "PASSED",
    "penultimate_status": "PASSED",   
    "end_time":"2022-02-28T09:50:05Z" 
  } 
  {
    "id": "4321",   
    "status": "PASSED",  
    "penultimate_status": "UNKNOWN",
    "end_time": "2020-10-14T13:52:57Z"
 }

I want to get "status" and "end_time" of the newest run. Unfortunately the order is not fix. Meaning the newest run can be first in the list, but also last or in the middle...

jq


Solution 1:[1]

Use sort_by to bring the items in order, then extract the last item:

jq '
  [.nodes[].run_data]
  | sort_by(.end_time) | last
  | {status, end_time}
' test.json
{
  "status": "PASSED",
  "end_time": "2022-02-28T09:50:05Z"
}

To get the fields in another format, replace {status, end_time} with your format, e.g. "\(.end_time): Status \(.status)", and set the -r flag as this isn't JSON anymore but raw text.

Solution 2:[2]

You can use transpose to map each object with its end_time.

Here I have converted end_time to seconds since Unix epoch and outputted the object with largest seconds value (this is the newest).

[
[. | map(.end_time | strptime("%Y-%m-%dT%H:%M:%SZ") | mktime), [.[0], .[1]]] 
| transpose[] 
| .[1] += {secs: .[0]} | .[1]
] 
| sort_by(.secs) | last 
| {status, end_time}

Output

{
  "status": "PASSED",
  "end_time": "2022-02-28T09:50:05Z"
}

Demo

https://jqplay.org/s/w1z2n2drc7

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2