Search code examples
jsonselectkeyjq

jq del: Remove elements from a list


I want to delete the entries in a JSON list that have the "enabled" key with the value false.

The following jq cmd does select the false entries but now I want to remove those entries and keep the rest of the structure.

jq '.app.sig[] | select(.enabled==false)'  app-test.json

Example JSON input

{
  "app" : {
       "id" : "11111111",
       "name" : "test",
       "general" : {
           "allow" : "sdasdass",
       },
       "settings" : {
           "max" : "8192",
       },
       "sig" : [
           {
               "enabled" : true,
               "Staging" : false,
               "sId" : "200101556"
           },
           {
               "enabled" : false,
               "Staging" : false,
               "sId" : "200012071"
           },
           {
               "enabled" : true,
               "Staging" : false,
               "sId" : "200012002"
           },
       ],
       "version" : "v1",
   }
}

Any help appreciated.

Thanks


Solution

  • WIth a valid JSON input it's straightforward using del and select:

    del(.app.sig[] | select(.enabled | not))
    

    Demo

    Alternatively, use map to reset the array with what you want to keep:

    .app.sig |= map(select(.enabled))
    

    Demo

    In both cases, you can directly use the (possibly negated) boolean value within select. Output:

    {
      "app": {
        "id": "11111111",
        "name": "test",
        "general": {
          "allow": "sdasdass"
        },
        "settings": {
          "max": "8192"
        },
        "sig": [
          {
            "enabled": true,
            "Staging": false,
            "sId": "200101556"
          },
          {
            "enabled": true,
            "Staging": false,
            "sId": "200012002"
          }
        ],
        "version": "v1"
      }
    }