I have a JSON array with objects as items. Some of the objects have properties, some don't. How can I filter the list with jq to keep only non-empty objects in the list?
Input:
[
{},
{ "x": 42 },
{},
{ "y": 21 },
{},
{ "z": 13 }
]
Expected output:
[
{ "x": 42 },
{ "y": 21 },
{ "z": 13 }
]
I tried jq 'select(. != {})'
, but the result still contains all items.
CodePudding user response:
You need map
to make select
test individual objects:
jq 'map(select(. != {}))'
CodePudding user response:
map
is required to apply the filter to every item in the array. Then any
can be used: it will return true
for objects with at least one property, and false
if the object is empty.
$ jq -n '{} | any'
false
$ jq -n '{x:42} | any'
true
Solution:
map(select(any))
CodePudding user response:
Just use the del
filter:
jq 'del(.[] | select(length == 0))'
or
jq 'del(.[] | select(. == {}))'