From 16d0e528aa19ae2688460b1850adfd3737be4dcd Mon Sep 17 00:00:00 2001 From: pkoppstein Date: Tue, 11 Aug 2015 02:50:48 -0400 Subject: [PATCH] walk/1 --- builtin.c | 11 +++++++++++ docs/content/3.manual/manual.yml | 27 +++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/builtin.c b/builtin.c index 2fa498bb..990e24a9 100644 --- a/builtin.c +++ b/builtin.c @@ -1640,7 +1640,18 @@ static const char* const jq_builtins[] = { " else .[2]" " end" " end;", + + // # Apply f to composite entities recursively, and to atoms + "def walk(f):" + " . as $in" + " | if type == \"object\" then" + " reduce keys[] as $key" + " ( {}; . + { ($key): ($in[$key] | walk(f)) } ) | f" + " elif type == \"array\" then map( walk(f) ) | f" + " else f" + " end;", }; + #undef LIBM_DDD_NO #undef LIBM_DD_NO #undef LIBM_DDD diff --git a/docs/content/3.manual/manual.yml b/docs/content/3.manual/manual.yml index 0f1c2e92..89dcad2a 100644 --- a/docs/content/3.manual/manual.yml +++ b/docs/content/3.manual/manual.yml @@ -1522,6 +1522,33 @@ sections: - 4 - 16 + - title: "`walk(f)`" + body: | + + The `walk(f)` function applies f recursively to every + component of the input entity. When an array is + encountered, f is first applied to its elements and then to + the array itself; when an object is encountered, f is first + applied to all the values and then to the object. In + practice, f will usually test the type of its input, as + illustrated in the following examples. The first example + highlights the usefulness of processing the elements of an + array of arrays before processing the array itself. The second + example shows how all the keys of all the objects within the + input can be considered for alteration. + + examples: + - program: 'walk(if type == "array" then sort else . end)' + input: '[[4, 1, 7], [8, 5, 2], [3, 6, 9]]' + output: + - '[[1,4,7],[2,5,8],[3,6,9]]' + + - program: 'walk( if type == "object" then with_entries( .key |= sub( "^_+"; "") ) else . end ) + input: '[ { "_a": { "__b": 2 } } ]' + output: + - '[{"a":{"b":2}}]' + + - title: "`..`" body: |