Search

Dark theme | Light theme

September 26, 2023

jq Joy: Deleting Keys From An Object

jq is a powerful tool to work with JSON from the command-line. The tool has a lot of functions that makes our live easier. If we want to delete keys from an object we can use the del function and pass the key name as argument. The argument is actually a path expression so we can refer to a key name with .key, but also use jq expressions.

In the following examples we use the del function in several use cases:

$ jq --null-input '{
    "username": "mrhaki",
    "firstName": "Hubert",
    "lastName": "Klein Ikkink"
} | del(.username)'
{
  "firstName": "Hubert",
  "lastName": "Klein Ikkink"
}
$ jq --null-input '{
    "username": "mrhaki",
    "firstName": "Hubert",
    "lastName": "Klein Ikkink"
} | del(.username) | del(.lastName)'
{
  "firstName": "Hubert"
}

If we want to remove multiple keys at once we can pass multiple key names separated by comma to the del function:

$ jq --null-input '{
    "username": "mrhaki",
    "firstName": "Hubert",
    "lastName": "Klein Ikkink"
} | del(.username, .lastName)'
{
  "firstName": "Hubert"
}

We can use also jq path expressions for example to delete keys by index instead of key name:

$ jq --null-input '{
    "username": "mrhaki",
    "firstName": "Hubert",
    "lastName": "Klein Ikkink"
    } | del(.[keys_unsorted | .[0,2]])'
{
  "firstName": "Hubert"
}

Written with jq 1.7.