【发布时间】:2021-05-19 10:22:02
【问题描述】:
我有一些类似下面的 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 文件,其中包含 Name 键中的值以及数组中的所有“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"
]
}
]
我希望这是有道理的,如果我遗漏了什么,请告诉我。
【问题讨论】:
-
我已经编辑了您的示例输入以使其成为有效的 JSON,您可以 check 我没有搞砸任何事情吗?
-
请在问题中包含您的样本的预期输出。
-
@Aaron 非常感谢!我添加了一个额外的语句来证明这个失败。
-
@oguzismail 我已根据您的建议添加了输出。
-
您想要的输出的具体示例下次会有所帮助。
标签: json export-to-csv jq