Search

Dark theme | Light theme

October 9, 2023

jq Joy: Using Default Values With The Alternative Operator

jq is a powerful tool to work with JSON from the command-line. The tool has a lot of functions and operators that makes our live easier. One of the operators we can use is the alternative operator // which allows us to specify default values. If the value on the left side of the operator // is empty, null or false then the value on the right side is returned, otherwise the value itself is returned. The operator can be used multiple times if we want to have multiple fallbacks for a value we are checking.

In the following examples we use the // operator in different scenarios:

$ jq --null-input  '[42, "jq joy", null, false] | [.[] | . // "default"]'
[
  42,
  "jq joy",
  "default",
  "default"
]
$ jq --null-input 'empty // "value"'
"value"

We can chain the // operator to specify multiple fallback options:

$ jq --null-input '{"name": "mrhaki"} | {"alias": (.username // .user // "not available") }'
{
  "alias": "not available"
}
$ jq --null-input '{"user": "mrhaki"} | {"alias": (.username // .user // "not available") }'
{
  "alias": "mrhaki"
}

Written with jq 1.7.