我有以下从API返回的JSON:
{
"Statement": [{
"Sid": "Group1",
"Resource": "arn:aws:ecs:*:777744445555:task-rendition/${aws:PrincipalTag/Service}-*:*",
"Effect": "Allow"
},
{
"Sid": "Group2",
"Resource": [
"arn:aws:ecs:*:777744445555:task-definition/${aws:PrincipalTag/Service}-*:*",
"arn:aws:ecs:*:777744445555:task-petition/${aws:PrincipalTag/Service}-*:*",
"arn:aws:ecs:*:777744445555:task-fruition/${aws:PrincipalTag/Service}-*:*"
],
"Effect": "Allow"
}
]}当我应用这些命令时,我得到了不可靠的结果:
.Statement.Resource |长度--> 73错误的.Statement1.Resource |长度--> 3正确
第一个命令产生的数字等于该字符串中的字符数,这不是我所需要的。如何以更确定的方式实现1和3?
我的上下文是CentOS 7和JQ1.5上的bash shell脚本
发布于 2019-12-02 03:03:35
假设Resource可以是string或array类型
.Statement[].Resource | if type == "array" then length else 1 end将输出
1
3发布于 2019-12-02 03:08:17
您可以将长度部分转换为数组,对其进行扁平化(),然后通过管道将其传递给Resource ()以获得正确数量的元素。
$ cat api_return.json | jq '[.Statement[0].Resource] | flatten | length'
1发布于 2019-12-02 10:51:13
对于资源的总计数,无论它们被指定到哪里,您都可以考虑:
def sigma(s): reduce s as $x (0; .+$x);
sigma(.. | objects | select(.Resource).Resource
| if type == "array" then length else 1 end)https://stackoverflow.com/questions/59128837
复制相似问题