From 416e8ada7d101cbb6137ed1e7b0753774a8c2e81 Mon Sep 17 00:00:00 2001 From: pkoppstein Date: Wed, 5 Jul 2023 05:05:26 -0400 Subject: builtin: add pick(stream) pick(stream) works on both arrays and objects Restrictions on the dot-paths are specified in manual.yml See #2578 --- docs/content/manual/manual.yml | 18 ++++++++++++++++++ src/builtin.jq | 6 ++++++ tests/man.test | 8 ++++++++ 3 files changed, 32 insertions(+) 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"] -- cgit v1.2.3