Vidushi Rao
Vidushi Rao

Reputation: 37

Deleting an object from array based on a condition

{
   "name": "ford",
   "availableVersions": [
      {
         "version": 111,
         "count": 3
      },
      {
         "version": 122,
         "count": 2
      },
      {
         "version": 133,
         "count": 3
      }
                          ],
       "RealVersion": 133


}
{
   "name": "bmw",
   "availableVersions": [
     {
         "version": 144,
         "count": 1
     },
     {
      "version": 155,
      "count": 3
     }                  ],
     "RealVersion": 120

}

I have this demo.json file now if (count == 3). I want to delete the key value pair of count and the respective version. So my output should be like. I am using jq for parsing the json file

OUTPUT-

{
   "name": "ford",
   "availableVersions": [
      {
         "version": 122,
         "count": 2
      }
                          ],
       "RealVersion": 133


}
{
   "name": "bmw",
   "availableVersions": [
     {
         "version": 144,
         "count": 1
     }                  ],
     "RealVersion": 120

}

cat demo1 | jq .availableVersions[] | jq 'select(.count == 3)'

I am using this command which will select count and respective version but I am not sure how to delete it. Can anyone help me with this?

Upvotes: 2

Views: 587

Answers (1)

oguz ismail
oguz ismail

Reputation: 50795

Just remap availableVersions selecting objects whose count is not 3.

.availableVersions |= map(select(.count != 3))

Online demo

Upvotes: 4

Related Questions