jsonjqtext-manipulation

JQ: Remove empty arrays from JSON


I am having trouble deleting all empty arrays from a JSON file with jq.

I've tried:

walk(if type == "array" then map(select(length > 0)) else . end)

which removes empty strings, but the arrays stay in the document. Is there a way to remove the arrays completely? Thank you for your support.


Solution

  • You could walk through using .., select everything that is an empty array [] and set it to empty

    (.. | select(. == [])) |= empty
    

    Edit:

    In this comment, oguz ismail uses del() instead of |= empty which is the preferred approach if the empty arrays to be deleted may be located not only in an object {"a":[]} but also in a superordinate array ([[]]).

    del(.. | select(. == []))