我是 jq 新手,我有一个场景需要获取 json 文件中任何匹配值的父级(在特定级别)。以下是示例数据。
{
"DevOps": {
"us-east-1": {
"i-049aa9a3bddb4****": {
"AmiLaunchIndex": 0,
"ImageId": "ami-00068cd7555f543d5",
"InstanceId": "i-049aa9a3bddb4*****",
"InstanceType": "t2.nano",
"LaunchTime": "2019-11-24 18:39:25+00:00",
"Monitoring": {
"State": "disabled"
},
"Placement": {
"AvailabilityZone": "us-east-1a",
"GroupName": "",
"Tenancy": "default"
},
"PrivateDnsName": "ip-10-250-128-77.ec2.internal",
"PrivateIpAddress": "10.250.128.77",
"ProductCodes": [],
"PublicDnsName": "",
"Tags": [
{
"Key": "Name",
"Value": "Network-Test-Host"
}
],
},
"i-0368117434*****": {
"AmiLaunchIndex": 0,
"ImageId": "ami-078137ecf12552edf",
"InstanceId": "i-0368117434******",
"InstanceType": "c5.2xlarge",
"KeyName": "infra-systems-prod-key",
"LaunchTime": "2020-02-13 15:51:15+00:00",
"Monitoring": {
"State": "disabled"
},
"Placement": {
"AvailabilityZone": "us-east-1a",
"GroupName": "",
"Tenancy": "default"
},
"PrivateDnsName": "ip-10-250-138-161.ec2.internal",
"PrivateIpAddress": "10.250.138.161",
"ProductCodes": [],
"PublicDnsName": "",
"Tags": [
{
"Key": "Name",
"Value": "Network-Test-Host"
}
],
},
}
}
}
例如,如果我的搜索值为“10.250.128.77”,它应该获取父级 -“i-049aa9a3bddb4****”。如果该值为“Network-Test-Host”,它应该给我 2 个实例 ID 的列表(i-049aa9a3bddb4****、i-0368117434*****)。然后从这一点开始,我将能够遍历任意键并获取相应的值,例如主机名、ImageId、实例类型
非常感谢对此的任何帮助
答案1
您使用特定私有 IP 地址的查询:
jq '.DevOps."us-east-1" | map_values(select( .PrivateIpAddress == "10.250.128.77" ))' file
参数化以从命令行参数获取查询 IP 地址:
jq --arg addr 10.250.128.77 \
'.DevOps."us-east-1" | map_values(select( .PrivateIpAddress == $addr ))' file
您使用特定Key
标签的查询Value
:
jq '.DevOps."us-east-1" | map_values(select( IN(.Tags[]; {Key: "Name", Value: "Network-Test-Host"}) ))' file
参数化以从命令行参数中获取Key
和:Value
jq --arg Key Name --arg Value Network-Test-Host \
'.DevOps."us-east-1" | map_values(select( IN(.Tags[]; $ARGS.named) ))' file
这些命令将生成一个 JSON 文档,其中包含单个对象,其中包含输入文档.DevOps."us-east-1"
部分中与查询匹配的键+值。
每个命令的共同点是它们将select()
语句应用于该部分的值.DevOps."us-east-1"
。布尔表达式会有所不同,具体取决于您要使用查询测试的小节。布尔表达式计算结果的部分真的将被保留,而所有其他位都被删除。