Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a relative Path or a Wildcard in JQ

Is it possible to use a relative path or name in JQ like the XPath // ?

Or is it possible to use an wildcard in JQ like .level1.*.level3.element ?

like image 778
Mirko Ebert Avatar asked Sep 11 '14 06:09

Mirko Ebert


2 Answers

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.

like image 59
Jeff Mercado Avatar answered Nov 15 '22 10:11

Jeff Mercado


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"]))
like image 33
peak Avatar answered Nov 15 '22 10:11

peak