Can I use a relative Path or a Wildcard in JQ
That's what the ..
filter was meant to represent. The use would look like this:
.level1 | .. | .level3? .element
Note: you must use the ?
otherwise you'll get errors as it recurses down objects that do not have the corresponding property.
Two additional points relative to Jeff's answer:
(1) An alternative to using ?
is to use objects
, e.g.
.level1 | .. | objects | .level3.element
(2) Typically one will want to eliminate the nulls corresponding to paths that do NOT match the specified trailing keys. To eliminate ALL nulls, one option is to tack on the filter: select(. != null).
On the other hand, if one wants to retain nulls that do appear as values, then one possibility is to use paths
as follows:
.level1
| (paths | select( .[-2:] == ["level3", "element"])) as $path
| getpath($path)
(Since paths
produces a stream of arrays of strings, the above expression produces a stream of the values corresponding to paths ending in .level3.element)
Equivalently but as a one-liner:
.level1 | getpath(paths | select(.[-2:] == ["level3","element"]))