Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading