summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorStephen Dolan <mu@netsoc.tcd.ie>2013-05-13 16:15:49 +0100
committerStephen Dolan <mu@netsoc.tcd.ie>2013-05-13 16:15:49 +0100
commita625d2821ecb27b87266762545f88d7d4aa59d31 (patch)
tree82fb4a6e7920673fa7a2570178f22cc47dc07d37
parentd8706fd4607ee1b5b56debd4da39e3314739f126 (diff)
Add to_entries, from_entries and with_entries functions.
Closes #97.
-rw-r--r--builtin.c3
-rw-r--r--docs/content/3.manual/manual.yml25
2 files changed, 28 insertions, 0 deletions
diff --git a/builtin.c b/builtin.c
index 1516c6c6..2a48ba35 100644
--- a/builtin.c
+++ b/builtin.c
@@ -547,6 +547,9 @@ static const char* const jq_builtins[] = {
"def _assign(paths; value): value as $v | fold . as $obj (path(paths) as $p | $obj | setpath($p; $v));",
"def _modify(paths; update): fold . as $obj (path(paths) as $p | $obj | setpath($p; getpath($p) | update));",
"def recurse(f): ., (f | select(. != null) | recurse(f));",
+ "def to_entries: [keys[] as $k | {key: $k, value: .[$k]}];",
+ "def from_entries: map({(.key): .value}) | add;",
+ "def with_entries(f): to_entries | map(f) | from_entries;",
};
diff --git a/docs/content/3.manual/manual.yml b/docs/content/3.manual/manual.yml
index 2f36392c..766fef7b 100644
--- a/docs/content/3.manual/manual.yml
+++ b/docs/content/3.manual/manual.yml
@@ -478,6 +478,31 @@ sections:
input: '[[0,1], ["a","b","c"]]'
output: ['[false, true]']
+ - title: `to_entries`, `from_entries`, `with_entries`
+ body: |
+
+ These functions convert between an object and an array of
+ key-value pairs. If `to_entries` is passed an object, then
+ for each `k: v` entry in the input, the output array
+ includes `{"key": k, "value": v}`.
+
+ `from_entries` does the opposite conversion, and
+ `with_entries(foo)` is a shorthand for `to_entries |
+ map(foo) | from_entries`, useful for doing some operation to
+ all keys and values of an object.
+
+ examples:
+ - program: 'to_entries'
+ input: '[{"a": 1}, {"b": 2}]'
+ output: ['[{"key":"a", "value":1}, {"key":"b", "value":2}]']
+ - program: 'from_entries'
+ input: '[{"key":"a", "value":1}, {"key":"b", "value":2}]'
+ output: ['[{"a": 1}, {"b": 2}]']
+ - program: 'with_entries(.key |= "KEY_" + .)'
+ input: '[{"a": 1}, {"b": 2}]'
+ output: ['[{"KEY_a": 1}, {"KEY_b": 2}]']
+
+
- title: `select`
body: |