我如何在“,”后添加逗号来添加"arn:aws:iam::xxxxxxx:role/3"
下面的行。"arn:aws:iam::xxxxxxx:role/2"
"arn:aws:iam::xxxxxxx:role/2"
前:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "ec2.amazonaws.com"
},
"Action": "sts:AssumeRole"
},
{
"Effect": "Allow",
"Principal": {
"AWS": [
"arn:aws:iam::xxxxxxx:role/1",
"arn:aws:iam::xxxxxxx:role/2"
]
},
"Action": "sts:AssumeRole"
}
]
}
后
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "ec2.amazonaws.com"
},
"Action": "sts:AssumeRole"
},
{
"Effect": "Allow",
"Principal": {
"AWS": [
"arn:aws:iam::xxxxxxx:role/1",
"arn:aws:iam::xxxxxxx:role/2",
"arn:aws:iam::xxxxxxx:role/3"
]
},
"Action": "sts:AssumeRole"
}
]
}
答案1
请勿尝试使用标准文本处理工具(例如awk
)sed
或不使用 JSON 模块来解析 JSON 文本perl
,因为它们不了解 JSON 语法。jq
是一个轻量级的 JSON 处理器,可让您即时操作内容。
例如您的要求可以简单地写成
jq --arg new "arn:aws:iam::xxxxxxx:role/3" \
'.Statement[].Principal.AWS? += [$new]' json
如果有多个元素需要附加,则将参数创建为 JSON blob
jq --argjson new \
'["arn:aws:iam::xxxxxxx:role/3", "arn:aws:iam::xxxxxxx:role/4"]' \
'.Statement[].Principal.AWS? += $new'
如果内容在文件中,而你想永久修改此文件,请使用 GNU moreutils 包中提供的就地编辑工具,sponge
你可以这样做
jq --arg new "arn:aws:iam::xxxxxxx:role/3" \
'.Statement[].Principal.AWS? += [$new]' json | sponge json
或者使用类似 POSIX 工具mktemp
temp="$(mktemp)"
jq --arg new "arn:aws:iam::xxxxxxx:role/3" \
'.Statement[].Principal.AWS? += [$new]' json > "$temp" && mv "$temp" json