10

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 ?

Mirko Ebert
  • 1,349
  • 1
  • 18
  • 36

2 Answers2

13

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.

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
9

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"]))
peak
  • 105,803
  • 17
  • 152
  • 177
  • 2
    Thanks for the way to eliminate nulls: `.level1 | .. | objects | .level3.element | select(. != null)` – nik Sep 05 '17 at 07:50
  • I tried the same in my jq command, but I do not get any errors or output. Could you please let me know what am doing wrong here? `jq --slurpfile newval auth.json '.paths | .. | objects | .get.parameters += $newval' test.json > test1.json` – AK123 Aug 21 '19 at 10:56