diff options
author | pkoppstein <pkoppstein@gmail.com> | 2023-07-05 05:05:26 -0400 |
---|---|---|
committer | Nico Williams <nico@cryptonector.com> | 2023-07-05 23:48:31 -0500 |
commit | 416e8ada7d101cbb6137ed1e7b0753774a8c2e81 (patch) | |
tree | 72e7bef6fda48ea219d0bbf7df17fb0d0fefe4dc | |
parent | a881532b29ae8eabe79678c55a37f2b19ac5e624 (diff) |
builtin: add pick(stream)
pick(stream) works on both arrays and objects
Restrictions on the dot-paths are specified in manual.yml
See #2578
-rw-r--r-- | docs/content/manual/manual.yml | 18 | ||||
-rw-r--r-- | src/builtin.jq | 6 | ||||
-rw-r--r-- | tests/man.test | 8 |
3 files changed, 32 insertions, 0 deletions
diff --git a/docs/content/manual/manual.yml b/docs/content/manual/manual.yml index 16d17c07..396b7643 100644 --- a/docs/content/manual/manual.yml +++ b/docs/content/manual/manual.yml @@ -925,6 +925,24 @@ sections: input: '{"a": 1, "b": 2, "c": 3}' output: ['{"a": 2, "b": 3, "c": 4}'] + - title: "`pick(stream)`" + body: | + + Emit the projection of the input object or array defined by the specified stream of + dot-path specifications, such that if p is one of these specifications, + and `(. | p)` evaluates to $x, then `pick(stream) | p` will also be $x. + For arrays, negative indices and .[m:n] specifications should not be used. + + examples: + - program: 'pick(.a, .b.c, .x)' + input: '{"a": 1, "b": {"c": 2, "d": 3}, "e": 4}' + output: ['{"a":1,"b":{"c":2},"x":null}'] + + - program: '[1,2,3,4] | pick(.[2], .[0], .[0])' + input: '[1,2,3,4]' + output: ['[1,null,3]'] + + - title: "`path(path_expression)`" body: | diff --git a/src/builtin.jq b/src/builtin.jq index c6085552..0d42efd9 100644 --- a/src/builtin.jq +++ b/src/builtin.jq @@ -260,6 +260,12 @@ def walk(f): else f end; +# stream should be a stream of dot-paths +def pick(stream): + . as $in + | reduce path(stream) as $a (null; + setpath($a; $in|getpath($a)) ); + # SQL-ish operators here: def INDEX(stream; idx_expr): reduce stream as $row ({}; .[$row|idx_expr|tostring] = $row); diff --git a/tests/man.test b/tests/man.test index 9815878d..833837f3 100644 --- a/tests/man.test +++ b/tests/man.test @@ -219,6 +219,14 @@ map_values(.+1) {"a": 1, "b": 2, "c": 3} {"a": 2, "b": 3, "c": 4} +pick(.a, .b.c, .x) +{"a": 1, "b": {"c": 2, "d": 3}, "e": 4} +{"a":1,"b":{"c":2},"x":null} + +[1,2,3,4] | pick(.[2], .[0], .[0]) +[1,2,3,4] +[1,null,3] + path(.a[0].b) null ["a",0,"b"] |