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

Filtering JSON using jq with a condition

I have the following JSON:

{
  "LaunchTemplates": [
    {
      "LaunchTemplateName": "bla-99",
      "CreateTime": "2022-12-13T13:40:33+00:00"
    },
    {
      "LaunchTemplateName": "abcabc",
      "CreateTime": "2022-12-13T09:58:14+00:00"
    },
    {
      "LaunchTemplateName": "bla-34",
      "CreateTime": "2022-12-13T13:58:56+00:00"
    },
    {
      "LaunchTemplateName": "bla-222",
      "CreateTime": "2022-12-11T13:58:56+00:00"
    },
    {
      "LaunchTemplateName": "bla-233",
      "CreateTime": "2022-12-10T13:58:56+00:00"
    }
  ]
}

I want to filter the JSON and print the oldest templates after filtering. I have the following jq query that prints the template names after filtering:

file.json | jq  '.LaunchTemplates[].LaunchTemplateName|select(startswith("bla"))'

Output:

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

bla-99
bla-34
bla-222
bla-233

Now i want to add more logic to the query, and do something like that: If the number of bla lines is bigger than 3, then print the oldest bla lines (according to the date field). In my case, the output should be:

bla-233

Is that possible with jq or other shell commands? If so, how?

>Solution :

If you are only interested in the last two elements (and ignoring the fact that the input in the question is invalid JSON):

.LaunchTemplates
| sort_by(.CreateTime)
| map(.LaunchTemplateName|select(startswith("")))[:-3]
| reverse[]
  • sort_by(.CreateTime) sorts ascending by the CreateTime property.
  • map(.LaunchTemplateName|select(startswith("bla")) maps the input array to an array containing only the template names with a "bla" prefix.
  • [:-3] slices the input array to drop the last 3 elements (i.e. dropping the 3 newest elements.
  • reverse[] reverses the array and streams its elements.

Output:

"bla-222"
"bla-233"
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