How to change json object using jq bash

Viewed 94

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

1 Answers

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"
    ]
  }
}
Related