4

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"
    }
  ]
}
peak
  • 105,803
  • 17
  • 152
  • 177
keeer
  • 783
  • 1
  • 5
  • 11

1 Answers1

10

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

customcommander
  • 17,580
  • 5
  • 58
  • 84