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.

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! It is exactly what I was looking for.
@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"? and What should I do when someone answers my question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.