I have a json like that :
[
{"data":"a"},
{"data":"b"},
{"data":"c"}
]
using jq I want to add an incremental id field like that:
[
{"data":"a","id":"xx_1"},
{"data":"b","id":"xx_2"},
{"data":"c","id":"xx_3"}
]
I can't seem to get the right jq command for that, anyone?
Here's one way:
to_entries | map( (.value.id = "xx_\(1+.key)" ) | .value)
Here's another method, which however requires jq 1.5:
def add_id(prefix):
[ foreach .[] as $o (0;
. + 1;
$o + {"id": (prefix + tostring) }) ];
add_id("xx_")
Example:
$ jq -c -f add_id.jq
[ {"data":"a"}, {"data":"b"}, {"data":"c"} ]
Output:
[{"data":"a","id":"xx_1"},{"data":"b","id":"xx_2"},{"data":"c","id":"xx_3"}]
A third approach would be to use transpose
:
def add_id(prefix):
[ ., [ range(0;length) | {"id": (prefix + tostring) } ] ]
| transpose | map(add);
(If your jq does not have transpose/0, it's jq definition can readily be found, e.g. by googling.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With