Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject the array indices of objects in an array into the objects, using jq

Tags:

indexing

jq

Given an array of objects, I would like to inject a property with its position in the array. For example:

[ { "w" : "Hello" }, { "w" : "World } ]

I would like to produce:

[ { "w" : "Hello", p: 0 }, { "w" : "World, p:1 } ]

where p is the zero-based position in the array.

Is there a way to get the index of the element? I tried this but it is not working:

    keys[] as $i | [ .[] | .p= $i ] 

I get:

 [ { "w" : "Hello", p: 0 }, { "w" : "World, p:0 } ]
like image 728
cerebrotecnologico Avatar asked Dec 09 '25 05:12

cerebrotecnologico


1 Answers

You could do it like this:

[ keys[] as $i | .[$i] | .p=$i ]

Alternatively, you could make it work using to_entries like this:

[ to_entries[] | (.value.p=.key).value ]

Both of which yields:

[
  {
    "w": "Hello",
    "p": 0
  },
  {
    "w": "World",
    "p": 1
  }
]
like image 138
Jeff Mercado Avatar answered Dec 11 '25 12:12

Jeff Mercado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!