jqlang / jq

Command-line JSON processor
https://jqlang.github.io/jq/
Other
29.59k stars 1.54k forks source link

Please add nullish coalescing operator "??" to JQ? #3098

Closed elmaimbo closed 2 months ago

elmaimbo commented 2 months ago

I feel that the way the alternative operator // handles the value false is problematic, given that 'falsey' values of other types (such as the number 0 or the empty string "") aren't treated in the same way.

The // documentation mentions:

This is useful for providing defaults: .foo // 1 will evaluate to 1 if there's no .foo element in the input.

However if you adapt this example to .foo // true then you'll end up with true in the case where the .foo has the value false in the input. The solution is rather clumsy: if .foo == null then true else .foo end

I feel that a 'nullish coalescing operator', similar to the ?? operator used in JavaScript, would be far more useful. And since changing the behaviour of // has the potential to create problems for existing scripts, I'd like to request the addition of the ?? infix operator for JQ, which has the same semantics as // except that false is treated the same as any other (non-null) value?

To paraphrase the // documentation:

The ?? operator produces all the values of its left-hand side that are not null. If the left-hand side produces no values other than null, then ?? produces all the values of its right-hand side. A filter of the form a ?? b produces all the results of a that are not null. If a produces no results, or no results other than null, then a ?? b produces the results of b. ...

Thanks.

wader commented 2 months ago

Hello, agreed! have a look at https://github.com/jqlang/jq/issues/2042 discussion this

emanuele6 commented 2 months ago

I also want this, best proposed syntax currently is ///. ?? probably is not a good option because it may be confused with the ? operator:

foo?? - bar

That currently means:

(try (try foo catch empty) catch empty) - (bar)

Will become

(foo) ?? (-(bar))

But, at the same time, it doesn't make much sense to use the ? two times in a row.

Anyway, closing as duplicate

wader commented 2 months ago

@elmaimbo if you want to experiment see this comment https://github.com/jqlang/jq/issues/2042#issuecomment-2082697844