How to "number" array items?

Viewed 155

Considering input:

[
  {
    "a": 1
  },
  {
    "a": 2
  },
  {
    "a": 7
  }
]

how do I add new field to each object, which value would be index in array? Producing:

[
  {
    "a": 1,
    "index": 0
  },
  {
    "a": 2,
    "index": 1
  },
  {
    "a": 7,
    "index": 2
  }
]
5 Answers

Using reduce, without disassembling/reassembling the input:

reduce range(length) as $index (.; .[$index] += {$index})

Online demo

Store the structure into a variable, then use keys to get the indices, retrieve the corresponding object from the variable using the index and add the index to it:

jq '[ . as $d | keys[] | $d[.] + {index:.} ]' file.json

to_entries takes an object and returns an array of key/value pairs. It can be used effectively and intuitively.

input file

// file.json
[
    {
      "a": 1
    },
    {
      "a": 2
    },
    {
      "a": 7
    }
]

commands

jq 'to_entries | map(.value+{index:.key})' file.json

results

[
  {
    "a": 1,
    "index": 0
  },
  {
    "a": 2,
    "index": 1
  },
  {
    "a": 7,
    "index": 2
  }
]

Here's also an alternative (non-jq) solution, using jtc:

bash $ <input.json jtc -w'[:]<I>k' -i'{"index":{I}}'
[
   {
      "a": 1,
      "index": 0
   },
   {
      "a": 2,
      "index": 1
   },
   {
      "a": 7,
      "index": 2
   }
]
bash $ 

PS. I'm a developer of jtc - unix JSON processor
PPS. The disclaimer is required by SO.

Try : Array[index_of_object].property = value
for example : array[0].a = 1
Related