Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 913
mps Avatar asked Aug 22 '19 14:08

mps


2 Answers

This gets the desired result in jq.

jq 'del(..|.remove?)'
like image 86
user197693 Avatar answered Sep 22 '22 21:09

user197693


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

like image 36
Dmitry Avatar answered Sep 18 '22 21:09

Dmitry