cogitoergosum
cogitoergosum

Reputation: 2471

Replacing variables in JSON document

I am working with this example for the following input JSON document using cat input.json | jq --arg REGION "ap-south-1" --arg ACCOUNTID "46311000000" --arg QNAME "orders". However, the output does not show any transformation.

Can you please advise how to apply the replacement?

input.json

{
  "Version": "2012-10-17",
  "Id": "policy-15122020",
  "Statement": [
    {
      "Sid": "1",
      "Effect": "Allow",
      "Principal": {
        "AWS": "*"
      },
      "Action": [
        "sqs:ReceiveMessage",
        "sqs:SendMessage"
      ],
      "Resource": "arn:aws:sqs:$REGION:$ACCOUNTID:$QNAME",
      "Condition": {
        "StringEquals": {
          "aws:SourceAccount": "$ACCOUNTID"
        }
      }
    }
  ]
}

Upvotes: 0

Views: 152

Answers (2)

peak
peak

Reputation: 116690

In a jq program, "$ACCOUNTID" is a string whereas $ACCOUNTID is a jq variable. In other words, the approach you seem to be adopting would require dropping the quotation marks for this particular variable, similar changes for the others, and reading the template file as a jq program, not as a JSON file.

Upvotes: 1

oguz ismail
oguz ismail

Reputation: 50750

With JQ 1.6, you can use $ARGS builtin variable in conjunction with gsub and a named capturing group to achieve this.

jq --arg REGION "ap-south-1" \
   --arg ACCOUNTID "46311000000" \
   --arg QNAME "orders" '
walk(
  if type == "string" 
  then gsub("\\$(?<name>\\w+)"; $ARGS.named[.name])
  else . end
)' input.json

Upvotes: 2

Related Questions