使用 JMESPath 计算数组中的实例数

问题描述 投票:0回答:2

在这个问题底部的示例 JSON 中,我如何使用 JMESPath 计算数组中键/值对的数量

"Tags"

根据 JMESPath 文档,我可以使用

count()
函数 -

例如,以下表达式创建一个数组,其中包含 foo 对象中的元素总数,后跟 foo["bar"] 的值。

然而,文档似乎不正确。使用 JMESPath 网站,查询

Reservations[].Instances[].[count(@), Tags]
产生结果
[ [ null ] ]
。然后我通过AWS命令行测试,返回错误-

未知函数:count()

实际上有一种使用 JMESPath 来做到这一点的方法吗?

示例 JSON -

{
    "Reservations": [
        {
            "Instances": [
                {
                    "InstanceId": "i-asdf1234",
                    "InstanceName": "My Instance",
                    "Tags": [
                        {
                            "Value": "Value1",
                            "Key": "Key1"
                        },
                        {
                            "Value": "Value2",
                            "Key": "Key2"
                        },
                        {
                            "Value": "Value3",
                            "Key": "Key3"
                        },
                        {
                            "Value": "Value4",
                            "Key": "Key4"
                        }
                    ]
                }
            ]
        }
    ]
}
arrays json syntax jmespath
2个回答
30
投票

这里的答案是 JMESPath 文档令人震惊,并且由于某种原因我看到了过时的文档(检查屏幕右下角以查看您正在查看的版本。

我可以使用

length()
功能做我需要做的事-

Reservations[].Instances[].Tags[] | length(@)

16
投票

我设法将长度的这种用法

length(Tags[*])
纳入我认为有用并想分享的更大的声明中:

aws ec2 describe-instances --region us-west-2 --query 'Reservations[*].Instances[*].{id: InstanceId, ami_id: ImageId, type: InstanceType, tag_count: length(Tags[*])}' --profile prod --output table;

--------------------------------------------------------------------
|                         DescribeInstances                        |
+--------------+-----------------------+------------+--------------+
|    ami_id    |          id           | tag_count  |    type      |
+--------------+-----------------------+------------+--------------+
|  ami-abc123  |  i-redacted1          |  1         |  m3.medium   |
|  ami-abc456  |  i-redacted2          |  7         |  m3.xlarge   |
|  ami-abc789  |  i-redacted3          |  12        |  t2.2xlarge  |
+--------------+-----------------------+------------+--------------+
© www.soinside.com 2019 - 2024. All rights reserved.