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

Is it possible to nest select expressions in jq?

I have this input data:

{
    "xs": [
        {
            "id": "a",
            "ts": "2023-01-03"
        },
        {
            "id": "b",
            "ts": "2023-01-01"
        },
        {
            "id": "c",
            "ts": "2023-01-02"
        }
    ]
}

I would like to select only element id=c because it is the first element, with a date greater than id=b‘s, if you sort the elements in xs by their ts field.

This works:

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

.xs | sort_by(.ts) | map(select(.ts > "2023-01-01")) | first

but I don’t want to hard code the date. I want to use another select to find it:

.xs | sort_by(.ts) | map(select(.ts > select(.id == "b").ts)) | first

that however returns the empty list.

Demo

>Solution :

Do it in two steps, store the temporary result in a variable and use it again in the next select()

.xs                                | 
sort_by(.ts)                       | 
( 
  map(select(.id == "b").ts) as $d | 
  map(select(.ts > $d[]))          | 
  first 
)

jqplay – demo

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