JSON Object Removal – How to Remove a Specific JSON Object from a File

command linejson

I have the following JSON data in a file:

{
  "packages": {
    "cc": {
      "name": "cc",
      "version": "3.1",
      "release": "0.4",
      "arch": "x86"
    },
    "code": {
      "name": "code",
      "version": "3.0",
      "release": "2.0.2",
      "arch": "x86"
    }
  }
}

I want to remove the whole code object from the file. How can I do that using a command-line tool?

Best Answer

To delete the .packages.code key and its value, using jq:

jq 'del(.packages.code)' file.json

To delete any entry under .packages whose .name key has the value code:

jq 'del(.packages[] | select(.name == "code"))' file.json

The same two commands, but they take the code string from a shell variable:

string=code

jq --arg key "$string" 'del(.packages[$key])' file.json

jq --arg key "$string" 'del(.packages[] | select(.name == $key))' file.json

Redirect the output to a new file and replace the old file with that if it looks ok.

Related Question