我得到了一些JSON,如下所示(我在这里过滤了输出):
[
{
"Tags": [
{
"Key": "Name",
"Value": "example1"
},
{
"Key": "Irrelevant",
"Value": "irrelevant"
}
],
"c7n:MatchedFilters": [
"tag: example_tag_rule"
],
"another_key": "another_value_I_dont_want"
},
{
"Tags": [
{
"Key": "Name",
"Value": "example2"
}
],
"c7n:MatchedFilters": [
"tag:example_tag_rule",
"tag: example_tag_rule2"
]
}
]
我想要创建一个csv文件,其值在名称键内,以及数组中的所有"c7n:MatchedFilters“。我做了几次尝试,但仍然没有得到预期的结果。下面有一些示例代码和输出:
#Prints the key that I'm after.
cat new.jq | jq '.[] | [.Tags[], {"c7n:MatchedFilters"}] | .[] | select(.Key=="Name")|.Value'
"example1"
"example2"
#Prints all the filters in an array I'm after.
cat new.jq | jq -r '.[] | [.Tags[], {"c7n:MatchedFilters"}] | .[] | select(."c7n:MatchedFilters") | .[]'
[
"tag: example_tag_rule"
]
[
"tag:example_tag_rule",
"tag: example_tag_rule2"
]
#Prints *all* the tags (including ones I don't want) and all the filters in the array I'm after.
cat new.jq | jq '.[] | [.Tags[], {"c7n:MatchedFilters"}] | select((.[].Key=="Name") and (.[]."c7n:MatchedFilters"))'
[
{
"Key": "Name",
"Value": "example1"
},
{
"Key": "Irrelevant",
"Value": "irrelevant"
},
{
"c7n:MatchedFilters": [
"tag: example_tag_rule"
]
}
]
[
{
"Key": "Name",
"Value": "example2"
},
{
"c7n:MatchedFilters": [
"tag:example_tag_rule",
"tag: example_tag_rule2"
]
}
]
我希望这是有意义的,如果我错过了什么,请告诉我。
发布于 2021-05-19 13:40:21
您的尝试不起作用,因为您从[.Tags[], {"c7n:MatchedFilters"}]
开始构建一个包含所有标记的数组和一个包含过滤器的对象。然后,您很难找到一种方法来一次处理整个数组,因为它不加区分地将这些无关的东西混合在一起。如果你一开始不把它们结合起来,你会发现容易得多!
您希望找到带有Key
of "Name"
的单个标记。有一种方法可以找到:
first(
.Tags[]|
select(.Key=="Name")
).Value as $name
通过使用变量绑定,我们可以将其保存到以后,并考虑单独构造数组。
您说(在注释中),您只想将过滤器与空格连接起来。你可以很容易做到这一点:
(
."c7n:MatchedFilters"|
join(" ")
) as $filters
您可以将所有这些合并在一起,如下所示。请注意,每个变量绑定都使输入流保持不变,因此很容易组合所有内容。
jq --raw-output '
.[]|
first(
.Tags[]|
select(.Key=="Name")
).Value as $name|
(
."c7n:MatchedFilters"|
join(" ")
) as $filters|
[$name, $filters]|
@csv
希望这是足够容易阅读和分离出每一个概念。我们将数组分解成一个对象流。对于每个对象,我们找到名称并将其绑定到$name
,将过滤器连接起来并绑定到$filters
,然后构造一个包含两者的数组,然后将数组转换为CSV字符串。
我们不需要使用变量。我们可以让一个大型数组构造函数围绕表达式来查找名称,并让表达式找到筛选器。但我希望你能看到这些变量会使事情变得更平淡,更容易理解。
https://stackoverflow.com/questions/67601395
复制相似问题