How can I use a relative Path or a Wildcard in JQ
Asked Answered
S

2

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 ?

Seamaid answered 11/9, 2014 at 6:44 Comment(0)
G
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.

Gay answered 11/9, 2014 at 7:9 Comment(2)
Thanks for your answer, i will test it. The questionmark is only a question mark and not a wildcard char :-)Seamaid
The "wildcard" part is the .., not the ?. The ? just ignores errors when trying to access a level3 property.Gay
P
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"]))
Pederson answered 30/12, 2015 at 6:55 Comment(2)
Thanks for the way to eliminate nulls: .level1 | .. | objects | .level3.element | select(. != null)Pisano
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.jsonMonospermous

© 2022 - 2024 — McMap. All rights reserved.