使用jq从数组中删除空字符串?

19
如何在jq中从数组中删除空字符串项?
这是我的最佳猜测,但它似乎不起作用: 尝试
echo '["bob","","tim",""]' | jq '[ . [] | if length > 0 then . end ]'

期望输出:

["bob", "tim"]

错误:

. [] | 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
1个回答

39

加上 "else empty" 就可以得到正确的结果。

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

考虑使用 select 代替。

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

由于map(x)相当于[.[] | x],因此我们可以这样做。

jq 'map(select(length > 0))'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接