[英]jq - select objects with given key name
I've got an arbitrary structure with many levels, etc. I need to select all objects that contain a key named updateDate
. 我有一个具有多个级别的任意结构,等等。我需要选择包含名为
updateDate
的键的所有对象。 How do I do that with jq? 我怎么用jq做到这一点? I came up with one way but it also produces errors on invalid data types when it visits a leaf which I have to grep out:
我想出了一种方法,但是当它访问一个我必须要写的叶子时,它也会在无效数据类型上产生错误:
jq 'recurse(.[]) | has("updateDate")' | grep -Fv error
I don't really understand how to also check for types or leaves and I suspect there is a simpler way to achieve what I want? 我真的不明白如何检查类型或叶子,我怀疑有一种更简单的方法来实现我想要的东西?
In 1.4 you can just: 在1.4中你可以:
jq '..|.updateDate?'
If you're stuck with 1.3 you can use a longer program like so: 如果你坚持使用1.3,你可以使用更长的程序,如下所示:
jq 'recurse(if type == "array" or type = "object" then .[] else empty end) | if type == "object" then .updateDate else empty end'
Not tested: how about jq 'recurse(.[]?) | objects | has("updateDate")'
未经测试:如何
jq 'recurse(.[]?) | objects | has("updateDate")'
jq 'recurse(.[]?) | objects | has("updateDate")'
jq 'recurse(.[]?) | objects | has("updateDate")'
? jq 'recurse(.[]?) | objects | has("updateDate")'
?
The accepted answer also produces null
for every object that doesn't have the key. 对于没有密钥的每个对象,接受的答案也会产生
null
。
What worked for me was: 对我有用的是:
jq '..|objects|.updateDate//empty'
The .updateDate//empty
part means: if .updateDate
is null
(or false
), skip it entirely. .updateDate//empty
部分表示:如果.updateDate
为null
(或false
),则完全跳过它。
This of course wouldn't work if you expect your key to have values of false
or null
. 如果您希望您的密钥具有
false
或null
值,那么这当然不起作用。 In that case, use this: 在这种情况下,使用此:
jq '..|objects|select(has("updateDate"))|.updateDate'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.