用变量替换值-jq

时间:2018-10-08 21:00:51

标签: json amazon-web-services environment-variables jq

我可以算出如何使用jq替换变量中的值

$ jq -n --arg name bar '{"name":$name}'

{
  "name": "bar"
}

但是我不确定如何替换多个值。

{
  ...
  "snstopic": {
    "topic-project1": "team-project1-dev",
    "topci-project2": "team-project2-dev",
    ...  (different json files have different number of sns topics)
  },
 ...
}

我设置了以下环境变量:

$ export AWS_DEFAULT_REGION=us-east-2
$ export AWS_ACCOUNT_ID=123456789012
$ export ARN_PREFIX="arn:aws:sns:${AWS_DEFAULT_REGION}:${AWS_ACCOUNT_ID}:"

我想得到如下输出

{
  ...
  "snstopic": {
    "topic-project1": "arn:aws:sns:us-east-2:123456789012:team-project1-dev",
    "topci-project2": "arn:aws:sns:us-east-2:123456789012:team-project2-dev",
    ...  (different json files have different number of sns topics
  },
 ...
}

如何在.snstopic中所有匹配的键中添加它?

1 个答案:

答案 0 :(得分:3)

简而言之:map_values是您的朋友。

假设您的模板位于文件template.json中。然后,以下脚本将执行指定的转换:

#!/bin/bash
# As far as this example is concerned,
# there is no need to export any variables
AWS_DEFAULT_REGION=us-east-2
AWS_ACCOUNT_ID=123456789012
ARN_PREFIX="arn:aws:sns:${AWS_DEFAULT_REGION}:${AWS_ACCOUNT_ID}:"

jq --arg prefix "$ARN_PREFIX" '
  .snstopic |= map_values($prefix + .)
' template.json

示例

template.json

{
  "snstopic": {
    "topic-project1": "team-project1-dev",
    "topci-project2": "team-project2-dev"
  }
}

输出:

{
  "snstopic": {
    "topic-project1": "arn:aws:sns:us-east-2:123456789012:team-project1-dev",
    "topci-project2": "arn:aws:sns:us-east-2:123456789012:team-project2-dev"
  }
}