1

I have the following json file:

{
  "actions": [
    {
      "values": "test",
      "features": [
        {
          "v1": 100,
          "v2": {
            "dates": [
              "2020-04-08 06:58:26",
              "2020-04-08 06:58:26"
            ]
          }
        }
      ]
    }
  ]
}

I would like to append n-times the object within the "actions" array to the end of it, creating n+1 total objects.

Expected output if n=2:

{
  "actions": [
    {
      "values": "test",
      "features": [
        {
          "v1": 100,
          "v2": {
            "dates": [
              "2020-04-08 06:58:26",
              "2020-04-08 06:58:26"
            ]
          }
        }
      ]
    },
    {
      "values": "test",
      "features": [
        {
          "v1": 100,
          "v2": {
            "dates": [
              "2020-04-08 06:58:26",
              "2020-04-08 06:58:26"
            ]
          }
        }
      ]
    },
    {
      "values": "test",
      "features": [
        {
          "v1": 100,
          "v2": {
            "dates": [
              "2020-04-08 06:58:26",
              "2020-04-08 06:58:26"
            ]
          }
        }
      ]
    }
  ]
}

I found this answer [How can I duplicate an existing object within a JSON array using jq? however it only works with one element at the end.

Inian
  • 80,270
  • 14
  • 142
  • 161
ana
  • 13
  • 3

1 Answers1

0

You can just use a reduce() function with range() together to create the index to include the object at.

jq --arg n 2 'reduce range(0, ($n|tonumber)) as $d (.; .actions[$d+1] += .actions[0] )' json
Inian
  • 80,270
  • 14
  • 142
  • 161
  • Thank you! It is exactly what I was looking for. – ana Apr 30 '20 at 11:27
  • @ana: if this worked, please click on the tick-mark next to answer to mark the post "resolved". See [What does it mean when an answer is "accepted"?](https://stackoverflow.com/help/accepted-answer) and [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) – Inian Apr 30 '20 at 11:29