Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq - select objects with given key name

Tags:

json

jq

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?

like image 233
Yuri Geinish Avatar asked Apr 24 '14 12:04

Yuri Geinish


2 Answers

In 1.4 you can just:

jq '..|.updateDate?'

If you're stuck with 1.3 you can use a longer program like so:

jq 'recurse(if type == "array" or type = "object" then .[] else empty end) | if type == "object" then .updateDate else empty end'
like image 92
user2259432 Avatar answered Sep 30 '22 04:09

user2259432


The accepted answer also produces null for every object that doesn't have the key.

What worked for me was:

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

The .updateDate//empty part means: if .updateDate is null (or false), skip it entirely.

This of course wouldn't work if you expect your key to have values of false or null. In that case, use this:

jq '..|objects|select(has("updateDate"))|.updateDate'
like image 41
Juan Campa Avatar answered Sep 30 '22 03:09

Juan Campa