user1424739
user1424739

Reputation: 13735

jq: error (at <stdin>:1): null (null) cannot be matched, as it is not a string

$ jq '.y | gsub(","; "-")' <<< '{"y": "a,b"}'
"a-b"
$ jq '.y | gsub(","; "-")' <<< '{"x": "a"}'
jq: error (at <stdin>:1): null (null) cannot be matched, as it is not a string

I got the above error. I can use if-else-end statement to solve the problem. But it is a little verbose.

What is the most succinct way to fix the error so that .y is still accessed with "," replaced by "-", but when .y does not exist, an empty string will be printed?

Upvotes: 1

Views: 5063

Answers (1)

pmf
pmf

Reputation: 36296

Add the Error Suppression Operator ? which defaults to empty

jq '.y | gsub(","; "-")?'

Demo

You may additionally add a default alternative using the Alternative Operator //

jq '.y | gsub(","; "-")? // ""'

Demo

Upvotes: 3

Related Questions