首页 > 解决方案 > 替换 JSON 文档中的变量

问题描述

我正在为以下输入 JSON 文档使用此示例cat input.json | jq --arg REGION "ap-south-1" --arg ACCOUNTID "46311000000" --arg QNAME "orders",使用. 但是,输出没有显示任何转换。

你能告诉我如何申请更换吗?

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

标签: jsonbashshelljq

解决方案


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

推荐阅读