Search code examples
jsonbashrecursionkeyjq

remove all values from JSON matching specific key


What is the easy way to delete arbitrary values from entire JSON by a specific label/key? My JSON may have an arbitrary depth, so deleting by the label should be done recursively. 

{
   "root": [
      {
         "name": "blah 1",
         "remove": [ 1, 2, 3 ],
         "new list": [
            {
               "name": "blah 2",
               "remove": null,
               "new list": [
                  {
                     "name": "blah 3",
                     "remove": [
                        {
                           "name": "blah 4",
                           "new list": []
                        },
                        {
                           "name": "blah 5",
                           "new list": []
                        }
                     ]
                  }
               ]
            },
            {
               "name": "blah 6",
               "new list": []
            }
         ]
      }
   ]
}

and I want to remove all the elements with the label "remove", so that the final result would look like this:

{
   "root": [
      {
         "name": "blah 1",
         "new list": [
            {
               "name": "blah 2",
               "new list": [
                  {
                     "name": "blah 3"
                  }
               ]
            },
            {
               "name": "blah 6",
               "new list": []
            }
         ]
      }
   ]
}

using sed/awk gives unexpected result (especially when there are nested object to be removed) so it must be a JSON aware utility like jq, or similar.


Solution

  • there's also an easy way to achieve the same using a walk-path based unix utility jtc:

    jtc -pw'<remove>l:' sample.json
    

    - it will delete recursively all occurrences of label "remove". If you like to apply the changes right into the source file (sample.json), then add option -f

    PS> Disclosure: I'm the creator of the jtc - shell cli tool for JSON operations