20

I've got an arbitrary structure with many levels, etc. I need to select all objects that contain a key named updateDate. How do I do that with 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?

4

3 回答 3

24

在 1.4 中,您可以:

jq '..|.updateDate?'

如果您坚持使用 1.3,您可以使用更长的程序,如下所示:

jq 'recurse(if type == "array" or type = "object" then .[] else empty end) | if type == "object" then .updateDate else empty end'
于 2014-06-19T06:44:32.240 回答
3

接受的答案也会null为每个没有密钥的对象生成。

对我有用的是:

jq '..|objects|.updateDate//empty'

.updateDate//empty部分的意思是:如果.updateDatenull(或false),则完全跳过它。

false如果您希望您的密钥具有or的值,这当然是行不通的null。在这种情况下,使用这个:

jq '..|objects|select(has("updateDate"))|.updateDate'
于 2018-12-07T19:54:32.893 回答
1

未测试:怎么样jq 'recurse(.[]?) | objects | has("updateDate")'

于 2014-06-19T06:44:43.240 回答