del(..|select(. == "null"))
This uses the recursive-descent operator ..
and select
function to find all the locations anywhere in the object with values that are equal to "null"
and gives them to del
. select
evaluates a boolean expression to decide whether to include a particular value or not, while ..
gives every single value in the tree to it, and del
accepts any expression that produces locations, which this does. (demo)
You can use the path
function to check what it's finding:
path(..|select(. == "null"))
and debug what it thinks you're trying to delete first. The output is an array of keys to follow recursively to reach the value, and so the final item in the array is the key that would actually be deleted.
You can also use update-assignment with |= empty
in jq 1.6 and up (it silently fails in earlier versions). You may or may not find this clearer: (..|select(. == "null")) |= empty
(demo) deletes those same keys.
If your values are true null
s, rather than the string "null"
, you can use the nulls
builtin function in place of the whole select
: del(..|nulls)
.
If your values are true nulls and you're using jq 1.5 (the current version in many distributions), you'll need to use recurse(.[]?; true)
in place of ..
. This is because null values are specifically excluded from ..
(because it's defined as recurse
, which is defined as recurse(.[]?)
, which is defined as recurse(.[]?; . != null)
). This behaviour changed to the (more useful) one above in 1.6, though the documentation hasn't changed, which appears to be a documentation bug.
SpatiaLite
and this database has manynull
values. When I export a part of this database withogr2ogr
as aGeoJSON
file it brings me all null values inside the database in thisGeoJSON
file. So this is a workaround to exclude all irrelevant data and make my JSON as small as possible. – raylight Jun 18 '21 at 16:37"null"
instead of the actual JSON valuenull
. – chepner Jun 18 '21 at 17:17null
... Writing the string"null"
was one typo that I made on the question. – raylight Jun 18 '21 at 18:44