Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an incremental index with jq

Tags:

json

bash

jq

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?

like image 672
UVRadiation Avatar asked Feb 09 '23 04:02

UVRadiation


1 Answers

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.)

like image 152
peak Avatar answered Feb 12 '23 09:02

peak