“Ternary operator” with JQ: Checking for empty values

As you noticed I use JQ commonly like RegExp. I recently used select(.!=null) to filter for non-null values. Turns out I missed something in docs:

jq -nc '{a:1},[1,23],true,null,42|values'

OUTPUT

{"a":1}
[1,23]
true
42
jq -nc '{a:1},[1,23],true,null,42|iterables'

OUTPUT

{"a":1}
[1,23]
jq -nc '{a:1},[1,23],true,null,42|nulls'

OUTPUT

null

Now that can be used to set defaults:

jq -nc '.notset?|values // "default"'

OUTPUT

"default"
$ jq -nc '.notset|values // "default"'

OUTPUT

"default"

Or just use it to do some little validation on expected input:

jq -nc '.notset|error("has no value")'

OUTPUT

jq: error (at <unknown>): has no value
jq -nc '{foo:"bar"}|(.baz|values // error("baz not set")|.'

OUTPUT

jq: error (at <unknown>): has no value
jq -nc '{foo:"bar"}|(.baz|values // error("baz not set")) as $e|.'
jq: error (at <unknown>): baz not set
jq -nc '{foo:"bar"}|(.foo|values // error("foo not set")) as $e|.'

OUTPUT

{"foo":"bar"}
jq -nc 'def chkkey(k): .[k]|values // error(k + "not set"), {foo:"bar"}|(.foo|values // error("foo is empty")) as $e|.'

OUTPUT

{"foo":"bar"}
jq -nc 'def notempty(k): .[k]|values // error(k + " is empty or not set"); {foo:"bar"}|notempty("foo")'

OUTPUT

"bar"
jq -nc 'def notempty(k): .[k]|values // error(k + " is empty or not set"); {baz:"bar"}|notempty("foo")'

OUTPUT

jq: error (at <unknown>): foo is empty or not set

Let’s turn it into a helper function:

jq -nc 'def notempty(k):
        . as $in
        |(
            (k|arrays // [k])[] as $k
            |$in[$k]|values // error($k + " is empty or not set")
        ) as $x
        |$in;

OUTPUT

{"foo":"bar","baz":"mar"}
jq -nc 'def notempty(k):
        . as $in
        |(
            (k|arrays // [k])[] as $k
            |$in[$k]|values // error($k + " is empty or not set")
        ) as $x
        |$in;
        {foo:"bar", baz: "mar"}|notempty(["meer"])'

OUTPUT

jq: error (at <unknown>): meer is empty or not set

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.