Raghavendra Kulkarni
Raghavendra Kulkarni

Reputation: 23

How to add section of json to the existing file using jq

I am using jq to parse a JSON file. I have some section of JSON file with below content

[
  {
    "PropagateAtLaunch": true,
    "Value": {
      "Ref": "TNAM"
    },
    "Key": "Name"
  },
  {
    "PropagateAtLaunch": true,
    "Value": {
      "Ref": "TAPP"
    },
    "Key": "application"
  },
  {
    "PropagateAtLaunch": true,
    "Value": {
      "Ref": "TENV"
    },
    "Key": "environment"
  },
  {
    "PropagateAtLaunch": true,
    "Value": {
      "Ref": "TSHA"
    },
    "Key": "shared"
  },
  {
    "PropagateAtLaunch": true,
    "Value": {
      "Ref": "TTER"
    },
    "Key": "tier"
  },
  {
    "PropagateAtLaunch": true,
    "Value": {
      "Ref": "CostCenter"
    },
    "Key": "cost-center"
  }
]

In this I want to add another section like:

{
  "Value": {
    "Ref": "TEAM"
  },
  "PropagateAtLaunch": true,
  "Key": "TEAM"
}

How can I add this new section?

This is the query I have used to extract the first section:

$ cat ABC.json | jq '.Resources.ASGRP.Properties.Tags'

Upvotes: 1

Views: 3032

Answers (2)

user3899165
user3899165

Reputation:

You can pass the object as a jq variable using --argjson, then use += to add the object to the array:

jq --argjson obj '{"sample": "object"}' '.Resources.ASGRP.Properties.Tags += [$obj]'

If you don't want the original object, use + instead of +=.

Upvotes: 5

Mustafa DOGRU
Mustafa DOGRU

Reputation: 4112

Try this "jq -s add ABC.json add.json" as below;

user@host:/tmp$ cat add.json
[
{
    "Value": {
    "Ref": "TEAM"
     },
     "PropagateAtLaunch": true,
         "Key": "TEAM"
     }
]
user@host:/tmp$ jq -s add ABC.json add.json  > ABCLAST.json
user@host:/tmp$ cat ABCLAST.json 
[
  {
    "PropagateAtLaunch": true,
    "Value": {
      "Ref": "TNAM"
    },
    "Key": "Name"
  },
  {
    "PropagateAtLaunch": true,
    "Value": {
      "Ref": "TAPP"
    },
    "Key": "application"
  },
  {
    "PropagateAtLaunch": true,
    "Value": {
      "Ref": "TENV"
    },
    "Key": "environment"
  },
  {
    "PropagateAtLaunch": true,
    "Value": {
      "Ref": "TSHA"
    },
    "Key": "shared"
  },
  {
    "PropagateAtLaunch": true,
    "Value": {
      "Ref": "TTER"
    },
    "Key": "tier"
  },
  {
    "PropagateAtLaunch": true,
    "Value": {
      "Ref": "CostCenter"
    },
    "Key": "cost-center"
  },
  {
    "PropagateAtLaunch": true,
    "Value": {
      "Ref": "TEAM"
    },
    "Key": "TEAM"
  }
]

Upvotes: 2

Related Questions