Skip to content

Commit

Permalink
paths now includes paths to nulls
Browse files Browse the repository at this point in the history
There are a few reasonable ways recurse could behave. The standard
libraries implemntation does the following:

`recurse(f;cond)` yields ., then . | f if . | f satisfies cond, then
                                 . | f | f if . | f | f satisfies cond,
                                 etc...

But it turns out that for paths, you want the following behavior:
`recurse(f;cond)` yields ., then . | f is . satisfies cond, then
                                 . | f | f if . | f satisfies cond,
                                 etc.

The difference is non-trivial (and there are actually a few degrees of
freedom here), so I gave paths its own definition, rather than adding a
new builtin. This means we don't have two builtin recurses floating
around.
  • Loading branch information
alex-ozdemir committed Jul 7, 2016
1 parent c87889e commit cc573c4
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/builtin.jq
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ def indices($i): if type == "array" and ($i|type) == "array" then .[$i]
else .[$i] end;
def index($i): indices($i) | .[0]; # TODO: optimize
def rindex($i): indices($i) | .[-1:][0]; # TODO: optimize
def paths: path(recurse(if (type|. == "array" or . == "object") then .[] else empty end))|select(length > 0);
def paths: def recurse_pre(f; cond): def r: ., (select(cond) | f | r); r;
path(recurse_pre(.[]?;.!=null))|select(length > 0);
def paths(node_filter): . as $dot|paths|select(. as $p|$dot|getpath($p)|node_filter);
def any(generator; condition):
[label $out | foreach generator as $i
Expand Down
10 changes: 10 additions & 0 deletions tests/jq.test
Original file line number Diff line number Diff line change
Expand Up @@ -743,6 +743,16 @@ path(.a[path(.b)[0]])
[1,[[],{"a":2}]]
[[0],[1],[1,0],[1,1],[1,1,"a"]]

# Make sure we get paths to nulls
[paths]
[1,null]
[[0],[1]]

# Make sure we don't get paths to lone items
[paths]
5
[]

[leaf_paths]
[1,[[],{"a":2}]]
[[0],[1,1,"a"]]
Expand Down

0 comments on commit cc573c4

Please sign in to comment.