user2925795
user2925795

Reputation: 398

Add the same element of array in a existing JSON using jq

I have a json file and I want to add some value from top in another place in json. I am trying to use jq command line.

{
    "channel": "mychannel",
    "videos": [
        {
            "id": "10",
            "url": "youtube.com"
        },
        {
            "id": "20", 
            "url": "youtube.com"
        }
    ]
}

The output would be:

{
    "channel": "mychannel",
    "videos": [
        {
            "channel": "mychannel",
            "id": "10",
            "url": "youtube.com"
        },
        {
            "channel": "mychannel",
            "id": "20", 
            "url": "youtube.com"
        }
    ]
}

in my json the "channel" is static, same value always. I need a way to concatenate always in each video array.

Someone can help me?

jq .videos + channel

Upvotes: 0

Views: 179

Answers (1)

chepner
chepner

Reputation: 531335

Use a variable to remember .channel in the later stages of the pipeline.

$ jq '.channel as $ch | .videos[].channel = $ch' tmp.json
{
  "channel": "mychannel",
  "videos": [
    {
      "id": "10",
      "url": "youtube.com",
      "channel": "mychannel"
    },
    {
      "id": "20",
      "url": "youtube.com",
      "channel": "mychannel"
    }
  ]
}

Upvotes: 3

Related Questions