删除所有空值 [英] Remove all null values
问题描述
我正在尝试使用jq从json对象中删除空值.我在他们的github上发现了此问题,所以现在我正在尝试用del
删除它们.
我有这个:
I am trying to remove null values from a json object using jq. I found this issue on their github and so now I'm trying to remove them with del
.
I have this:
'{ id: $customerId, name, phones: ([{ original: .phone },
{ original: .otherPhone}]), email} | del(. | nulls)'
这似乎没有任何作用.但是,如果我将nulls
替换为.phones
,则会删除电话号码.
This doesn't seem to do anything. However if I replace nulls
with .phones
it does remove the phone numbers.
推荐答案
以下内容说明了如何从JSON对象中删除所有空值键:
The following illustrates how to remove all the null-valued keys from a JSON object:
jq -n '{"a":1, "b": null, "c": null} | with_entries( select( .value != null ) )'
{
"a": 1
}
或者,paths/0
可以按如下方式使用:
Alternatively, paths/0
can be used as follows:
. as $o | [paths[] | {(.) : ($o[.])} ] | add
顺便说一句,del/1
也可以用于实现相同的结果,例如使用此过滤器:
By the way, del/1
can also be used to achieve the same result, e.g. using this filter:
reduce keys[] as $k (.; if .[$k] == null then del(.[$k]) else . end)
或更不明显,但更简洁:
Or less obviously, but more succinctly:
del( .[ (keys - [paths[]])[] ] )
出于记录,以下是使用delpaths/1
的两种方法:
And for the record, here are two ways to use delpaths/1
:
jq -n '{"a":1, "b": null, "c": null, "d":2} as $o
| $o
| delpaths( [ keys[] | select( $o[.] == null ) ] | map( [.]) )'
$ jq -n '{"a":1, "b": null, "c": null, "d":2}
| [delpaths((keys - paths) | map([.])) ] | add'
在这两种情况下,输出都是相同的: { "a":1 "d":2 }
In both these last two cases, the output is the same: { "a": 1, "d": 2 }
这篇关于删除所有空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!