jq

JQ:How to remove items from json array with conditions?


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

{
    "Sid": "bla1",
    "Effect": "Allow",
    "Principal": {
      "AWS": "*"
    },
    "Action": "blabla",
    "Resource": "blablablabla",
    "Condition": {
      "ArnLike": {
        "aws:bla": [
          "blablablablablabla*",
          "blablablablabla*",
          "blablablabla:*"
        ]
      }
    }
  }

How can i remove item "blablablablablabla:*" from "Condition->ArnLike->aws:bla" if "Sid" == "bla1"

expected result like below

{
    "Sid": "bla1",
    "Effect": "Allow",
    "Principal": {
      "AWS": "*"
    },
    "Action": "blabla",
    "Resource": "blablablabla",
    "Condition": {
      "ArnLike": {
        "aws:bla": [
          "blablablablabla*",
          "blablablabla:*"
        ]
      }
    }
  }

best regards


Solution

  • First, select the items that match the condition .Sid == "bla1", then delete from them any entry .Condition.ArnLike."aws:bla"[] that matches . == "blablablablablabla*".

    jq 'select(.Sid == "bla1") |=
      del(.Condition.ArnLike."aws:bla"[] | select(. == "blablablablablabla*"))
    '
    

    Demo

    If your objects are in an array, apply this using a map onto that array.

    jq 'map(select(.Sid == "bla1") |=
      del(.Condition.ArnLike."aws:bla"[] | select(. == "blablablablablabla*"))
    )'
    

    Demo