1

I have a json object that looks like below:

{
    "CallerReference": "terraform-20210518124856158900000001",
    "Aliases": {
        "Quantity": 3,
        "Items": [
            "consumer-portal.mlb.effi.com.au",
            "*.mlb.effi.com.au",
            "coolvalue.mylocalbroker.com.au"
        ]
    }
}

And I need to;

  1. First get the value of Quantity
  2. Increment it by 1
  3. Then change that value so it looks like "Quantity": 4,
  4. And I need to add another entry at the bottom of the Items array.

I am using jq and trying to first replace the "Quantity" value as below:

filename=cf.json
rm $filename
aws cloudfront get-distribution-config --id <ID> \
  --query 'DistributionConfig' --output json > $filename

etag=$(aws cloudfront  get-distribution-config --id <ID> |
       jq -r '.ETag')

aws cloudfront update-distribution \
  --distribution-config file://$filename --id <ID> --if-match $etag > /dev/null

jq --argjson i "10" '.Aliases.Quantity[$i]' $filename

But I am getting this error:

jq: error (at cf.json:136): Cannot index number with number

Thor
  • 45,082
  • 11
  • 119
  • 130
Jananath Banuka
  • 2,951
  • 8
  • 57
  • 105

1 Answers1

4

Sounds like += should to the trick [docs]

  • .Aliases.Quantity += 1 To increment Quantity by 1
  • .Aliases.Items += [ "Example" ] To add a new index to the Items array

Full command:

jq '.Aliases.Quantity += 1 | .Aliases.Items += [ "Example" ]'

Online demo

{
  "CallerReference": "terraform-20210518124856158900000001",
  "Aliases": {
    "Quantity": 4,
    "Items": [
      "consumer-portal.mlb.effi.com.au",
      "*.mlb.effi.com.au",
      "coolvalue.mylocalbroker.com.au",
      "Example"
    ]
  }
}
0stone0
  • 34,288
  • 4
  • 39
  • 64
  • Thanks, this is working, but how can I make the changes permanent? When I tried `jq '.Aliases.Quantity += 1 | .Aliases.Items += [ "Example" ]' $filename` it gives an output only but doesn't override the file though. – Jananath Banuka Jun 17 '21 at 13:56
  • Please take a look at [this question](https://stackoverflow.com/questions/36565295/jq-to-replace-text-directly-on-file-like-sed-i). You'll need to do something like: `jq ... $filename > temp.tmp && mv temp.tmp $filename` – 0stone0 Jun 17 '21 at 13:58
  • 1
    cool got it to work with `jq '.Aliases.Quantity += 1 | .Aliases.Items += [ "Example" ]' $filename > updatedcf.json` – Jananath Banuka Jun 17 '21 at 13:58