Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove blank strings from array with jq?

Tags:

json

arrays

jq

How does one remove blank string items from an array in jq?

This is my best guess, but it doesn't appear to work:

Attempt

echo '["bob","","tim",""]' | jq '[ . [] | if length > 0 then . end ]'

Desired output:

["bob", "tim"]

Error:

. [] | if length > 0 then . end                            
jq: error: Possibly unterminated 'if' statement at <top-level>, line 1:
. [] | if length > 0 then . end       
jq: 2 compile errors
like image 841
leeand00 Avatar asked May 31 '17 15:05

leeand00


1 Answers

Adding "else empty" gets the right result

jq '[ .[] | if length > 0 then . else empty end ]'

Consider using select instead.

jq '[ .[] | select(length > 0) ]'

And since map(x) is equivalent to [.[] | x], we can do this.

jq 'map(select(length > 0))'
like image 72
user197693 Avatar answered Sep 28 '22 19:09

user197693