João Amaro
João Amaro

Reputation: 496

Insert a new field into a specific object using JQ

I have a JSON file that looks like this:

{
  "BackupPlanName": "backup-plan",
  "Rules": [
    {
      "RuleName": "rule1",
      "Lifecycle": {
        "DeleteAfterDays": 35
      },
      "RuleId": "3e5ae513"
    },
    {
      "RuleName": "rule2",
      "Lifecycle": {
        "DeleteAfterDays": 365
      },
      "RuleId": "82c660c9"
    }
  ]
}

And I need to add this key/value to rule1 only:

"EnableContinuousBackup": true

If I use the below command, I add it too every object:

jq '.Rules[].EnableContinuousBackup += true'

With this one, it doesn't get me the full JSON:

jq '.Rules[] | select(.RuleName=="rule1") | .EnableContinuousBackup += true'

So, how can I make it work so my json looks like this in the end?

{
  "BackupPlanName": "backup-plan",
  "Rules": [
    {
      "RuleName": "rule1",
      "Lifecycle": {
        "DeleteAfterDays": 35
      },
      "RuleId": "3e5ae513",
      "EnableContinuousBackup": true
    },
    {
      "RuleName": "rule2",
      "Lifecycle": {
        "DeleteAfterDays": 365
      },
      "RuleId": "82c660c9",
    }
  ]
}

Upvotes: 1

Views: 396

Answers (1)

oguz ismail
oguz ismail

Reputation: 50750

You need to enclose the right hand side of the assignment operator (=, not +=) in parentheses.

(.Rules[] | select(.RuleName == "rule1") .EnableContinuousBackup) = true

Online demo

Upvotes: 2

Related Questions