Add to_entries, from_entries and with_entries functions.

Closes #97.
This commit is contained in:
Stephen Dolan committed 2013-05-13 16:15:49 +01:00
1 parent d8706fd460
commit a625d2821e
2 files changed
+28

No files matched your search

+3
View File
@@ -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;",
};
+25
View File
@@ -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: |