如何使用 JQ 提取此字段?
How do I extract this field using JQ?
JQ让我无理取闹,我鄙视它的存在。我已经尝试提取 tf-name
键的值 30 分钟,如果我必须再次尝试,我将成为隐士。请问,如何得到 tmp
作为结果?
➜ aws resourcegroupstaggingapi get-resources --tag-filters Key=tf-name,Values=tmp --profile=test | jq
{
"ResourceTagMappingList": [
{
"ResourceARN": "arn:aws:s3:::stack-hate-1234567890salt",
"Tags": [
{
"Key": "aws:cloudformation:stack-name",
"Value": "hatestack"
},
{
"Key": "aws:cloudformation:stack-id",
"Value": "arn:aws:cloudformation:us-west-2:6666666666666:stack/FSStack/hate-hate-hate-123456789"
},
{
"Key": "tf-name",
"Value": "tmp"
},
{
"Key": "aws:cloudformation:logical-id",
"Value": "hatebucket1234"
},
{
"Key": "aws-cdk:auto-delete-objects",
"Value": "true"
}
]
}
]
一旦您知道顶级对象的类型,提取起来就非常简单。你可以看到 ResourceTagMappingList
是一个记录列表,所以它后面应该有一个 []
符号,我认为大多数 jq
的初学者往往会错过。所以
.ResourceTagMappingList[].Tags | from_entries."tf-name"
应该可以得到您想要的值。参见 jqplay demo
它的工作方式是,from_entries
函数采用键名为 key
和 value
的对象数组,并将其转换为仅值对。从那里,我们只提取键名 tf-name
。需要特殊的双引号是因为这里的键名中包含一个meta-character -
,应该将整个字符串作为键名来对待。
另一种方法是使用如下所示的 select
语句
.ResourceTagMappingList[].Tags[] | select(.Key == "tf-name").Value
JQ让我无理取闹,我鄙视它的存在。我已经尝试提取 tf-name
键的值 30 分钟,如果我必须再次尝试,我将成为隐士。请问,如何得到 tmp
作为结果?
➜ aws resourcegroupstaggingapi get-resources --tag-filters Key=tf-name,Values=tmp --profile=test | jq
{
"ResourceTagMappingList": [
{
"ResourceARN": "arn:aws:s3:::stack-hate-1234567890salt",
"Tags": [
{
"Key": "aws:cloudformation:stack-name",
"Value": "hatestack"
},
{
"Key": "aws:cloudformation:stack-id",
"Value": "arn:aws:cloudformation:us-west-2:6666666666666:stack/FSStack/hate-hate-hate-123456789"
},
{
"Key": "tf-name",
"Value": "tmp"
},
{
"Key": "aws:cloudformation:logical-id",
"Value": "hatebucket1234"
},
{
"Key": "aws-cdk:auto-delete-objects",
"Value": "true"
}
]
}
]
一旦您知道顶级对象的类型,提取起来就非常简单。你可以看到 ResourceTagMappingList
是一个记录列表,所以它后面应该有一个 []
符号,我认为大多数 jq
的初学者往往会错过。所以
.ResourceTagMappingList[].Tags | from_entries."tf-name"
应该可以得到您想要的值。参见 jqplay demo
它的工作方式是,from_entries
函数采用键名为 key
和 value
的对象数组,并将其转换为仅值对。从那里,我们只提取键名 tf-name
。需要特殊的双引号是因为这里的键名中包含一个meta-character -
,应该将整个字符串作为键名来对待。
另一种方法是使用如下所示的 select
语句
.ResourceTagMappingList[].Tags[] | select(.Key == "tf-name").Value