Miura
Miura

Reputation: 45

jq select compare two max's of array within object

Let's say I have to following JSON file:

{
  "1.1.1.1": {
    "history_ban": [
      "2021-05-02 14:30",
      "2022-01-01 12:00"
    ],
    "history_unban": [
      "2021-05-09 14:30",
      "2022-01-08 12:00"
    ]
  },
  "2.2.2.2": {
    "history_ban": [
      "2022-01-16 07:00"
    ],
    "history_unban": []
  },
  "3.3.3.3": {
    "history_ban": [
      "2022-01-15 22:40"
    ]
  }
}

My goals is to get all the keys where:

  1. Max history_ban date is smaller than "2022-01-16 09:00"
  2. Max history_unban date is empty/non-existent or smaller then Max history_ban date

I believe I have the majority of the query working as I wanted, but the 'Compare max unban with max ban' is not working. My current (not working) query is as follows:

to_entries[] | select((.value.history_ban != null) and (.value.history_ban | max < "2022-01-16 09:00") and ((.value.history_unban | length == 0 ) or (.value.history_unban | max < .value.history_ban | max))) | .key

I know my error is within (.value.history_unban | max < .value.history_ban | max) because, if I replace it with (.value.history_unban | max < "somedate") I get a working query.

The error I get is

jq: error (at :22): Cannot index array with string "value" exit status 5

What do I need to do to select/compare these two max values?

Just to be sure, my expected result in this example is

Upvotes: 1

Views: 635

Answers (1)

pmf
pmf

Reputation: 36151

You could use the update operator // to introduce another constraint if history_unban is existent and not empty.

jq -r '
  to_entries[] | select(.value
    | (.history_ban | max) as $maxban
    | $maxban > "2022-01-16 09:00"
      and (.history_unban | length == 0 // $maxban > max)
  ).key
'
2.2.2.2
3.3.3.3

Demo

Upvotes: 1

Related Questions