JQ to map array to object with index - how to

Viewed 201

pretty simple:

What I have: '["a","b","c"]'

What I want:

{
  "1":"a",
  "2":"b",
  "3":"c"
}

What I am working with.

echo '["a","b","c"]' | jq '. | map({(index(.)) : (.)})'

What I am getting (it seems to be operating on successively smaller arrays):

 echo '["a","b","c"]' | jq '. | map(index((.)))'
[
  0,
  0,
  0
]
1 Answers

A functional solution:

[to_entries[] | {(.key+1|tostring): .value}] | add

Or, more succinctly:

with_entries(.key |= (1+.|tostring))

Or, more prosaically:

. as $in
| reduce range(0;length) as $i (null; 
    . + {($i+1|tostring): $in[$i]})
Related