Home > Software engineering >  Filtering JSON using jq with a condition
Filtering JSON using jq with a condition

Time:12-14

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:

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?

CodePudding user response:

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"
  • Related