[英]JQ - how to display objects based on on the value of objects in an array
I have a JSON file that looks like this:我有一个看起来像这样的 JSON 文件:
{
"InstanceId": "i-9KwoRGF6jbhYdZi823aE4qN",
"Tags": [
{
"Key": "blah",
"Value": "server-blah"
},
{
"Key": "environment",
"Value": "ops"
},
{
"Key": "server_role",
"Value": "appserver"
},
{
"Key": "Name",
"Value": "some_name"
},
{
"Key": "product",
"Value": "some_server"
}
]
}
{
...more objects like the above...
}
I need to display the InstanceId where "Key" == "environment" and "Value" == "ops".我需要在“Key”==“environment”和“Value”==“ops”的位置显示 InstanceId。 I have jq-1.6.我有jq-1.6。
If I say:如果我说:
cat source.json | jq '
{ InstanceId, Tags } |
(.Tags[] | select( .Key == "environment" ))
'
I get some of what I want, but I cannot figure out how to include InstanceId in the output nor how to incorporate the "and" part of the select.我得到了一些我想要的东西,但我不知道如何在 output 中包含 InstanceId,也不知道如何合并 select 的“和”部分。
Here is a simple but efficient approach using any
:这是使用any
的简单但有效的方法:
select( any(.Tags[]; .Key=="environment" and .Value == "ops") )
| .InstanceId
An alternative approach that avoids .Tags[]
:另一种避免.Tags[]
的方法:
{"Key": "environment", "Value": "ops"} as $object
| select( .Tags | index($object) )
| .InstanceId
I'm not sure if this is the exact output you're looking for (comment if it isn't), but this will output the InstanceId
s of JSON objects that contain a Tag
with Key
environment
and Value
ops
.我不确定这是否是您正在寻找的确切 output(如果不是,请发表评论),但这将 output ops
的InstanceId
包含Key
environment
的Tag
和 2F Value
对象。
jq 'select( .Tags[] | (.Key == "environment" and .Value == "ops")) | .InstanceId' < source.json
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.