day0ops
day0ops

Reputation: 7482

jq select with multiple conditions

I have the following few json objects that Id like to filter using a single jq command.

[
  {
    "version": "v2",
    "transactionId": "10590541.2280012772",
    "description": {
      "original": "DUMMY",
      "sanitized": "DUMMY A.B. C"
    }
  }
]

or

[
  {
    "version": "v2",
    "transactionId": "10590541.2280012772",
    "description": {
      "original": "DUMMY",
      "sanitized": "DUMMY A.B. C"
    },
    "merchantDetails": {
      "name": "DUMMY"
    }
  }
]

or

[
  {
    "version": "v2",
    "transactionId": "10590541.2280012772",
    "merchantDetails": {
      "name": "DUMMY"
    }
  }
]

Im trying to filter with jq so either of the above json objects satisfy the filter condition. In other words, if both .merchantDetails.name and .description.sanitized exist then .merchantDetails.name has to take precedence when checking for the string "DUMMY". If not then check either .merchantDetails.name or .description.sanitized for the string "DUMMY".

What i currently have is the following which doesn't really work.

jq . test.json  | jq '.[] | select( (.merchantDetails.name | try contains ("DUMMY")) or (.description.sanitized | try contains ("DUMMY")) )'

Anyway to achieve this using a single in-line jq command ?

Upvotes: 1

Views: 3346

Answers (1)

Inian
Inian

Reputation: 85780

You need a multi level conditional evaluation, because having to check different fields on different conditions

jq '
map (
  objects |
  if   has("merchantDetails") and has("description") then
    select( .merchantDetails.name  | contains("DUMMY"))
  elif has("merchantDetails") then
    select( .merchantDetails.name  | contains("DUMMY"))
  elif has("description") then
    select( .description.sanitized | contains("DUMMY"))
  else empty
  end
)
'

Upvotes: 2

Related Questions