Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i add an index in jq

Tags:

jq

I want to use jq map my input

["a", "b"]

to output

[{name: "a", index: 0}, {name: "b", index: 1}]

I got as far as

0 as $i | def incr: $i = $i + 1; [.[] | {name:., index:incr}]'

which outputs:

[
  {
    "name": "a",
    "index": 1
  },
  {
    "name": "b",
    "index": 1
  }
]

But I'm missing something.

Any ideas?

like image 507
Eric Hartford Avatar asked Jul 02 '14 10:07

Eric Hartford


2 Answers

It's easier than you think.

to_entries | map({name:.value, index:.key})

to_entries takes an object and returns an array of key/value pairs. In the case of arrays, it effectively makes index/value pairs. You could map those pairs to the items you wanted.

like image 151
Jeff Mercado Avatar answered Jan 01 '23 21:01

Jeff Mercado


A more "hands-on" approach is to use reduce: ["a", "b"] | . as $in | reduce range(0;length) as $i ([]; . + [{"name": $in[$i], "index": $i}])

like image 33
peak Avatar answered Jan 01 '23 22:01

peak