Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jq to add/prepend an element to the top of an array

Tags:

arrays

prepend

jq

I have the following json file (example.json):

{
  "examples": [
    {
      "example": "2"
    },
    {
      "example": "3"
    }
  ]
}

I'd like to use jq to add a new element to the top of this array (rather than the bottom). All the solutions I've come up with simply add it to the bottom (code I'm using below):

jq '.examples +=
[{"example": "1",
}]' example.json

The desired output (in case it's not immediately obvious) would be:

{
  "examples": [
    {
      "example": "1"
    },
    {
      "example": "2"
    },
    {
      "example": "3"
    }
  ]
}
like image 693
keeer Avatar asked Sep 05 '25 03:09

keeer


1 Answers

You can concatenate arrays with + so you can add your new object inside an array and concat the rest:

.examples |= [{example: "1"}] + .

https://jqplay.org/s/XIsoZ4GvOa

like image 192
customcommander Avatar answered Sep 07 '25 23:09

customcommander