gpt4 book ai didi

arrays - jq:选择列表中的.attribute

转载 作者:行者123 更新时间:2023-12-04 14:54:21 24 4
gpt4 key购买 nike

在python中,我可以执行以下操作:

>>> 5 in [2,4,6]
False
>>> 5 in [4,5,6]
True

确定列表中是否存在给定值 5。我想在 jq中做同样的概念。但是,没有 in。这是一个具有更实际数据集的示例,以及如何检查2个值。在我的真正需求中,我必须检查几百个并且不想将所有 or一起编辑。
jq '.[] | select(.PrivateIpAddress == "172.31.6.209"
or
.PrivateIpAddress == "172.31.6.229")
| .PrivateDnsName' <<EOF
[
{
"PrivateDnsName": "ip-172-31-6-209.us-west-2.compute.internal",
"PrivateIpAddress": "172.31.6.209"
},
{
"PrivateDnsName": "ip-172-31-6-219.us-west-2.compute.internal",
"PrivateIpAddress": "172.31.6.219"
},
{
"PrivateDnsName": "ip-172-31-6-229.us-west-2.compute.internal",
"PrivateIpAddress": "172.31.6.229"
},
{
"PrivateDnsName": "ip-172-31-6-239.us-west-2.compute.internal",
"PrivateIpAddress": "172.31.6.239"
}
]
EOF

最佳答案

使用,
我不知道在https://stedolan.github.io/jq/manual/v1.5/中记录了什么。但是答案是jq确实隐含了一对多和多对一的删减。

jq '.[] | select(.PrivateIpAddress == ("172.31.6.209",
"172.31.6.229"))
| .PrivateDnsName' <<EOF
[
{
"PrivateDnsName": "ip-172-31-6-209.us-west-2.compute.internal",
"PrivateIpAddress": "172.31.6.209"
},
{
"PrivateDnsName": "ip-172-31-6-219.us-west-2.compute.internal",
"PrivateIpAddress": "172.31.6.219"
},
{
"PrivateDnsName": "ip-172-31-6-229.us-west-2.compute.internal",
"PrivateIpAddress": "172.31.6.229"
},
{
"PrivateDnsName": "ip-172-31-6-239.us-west-2.compute.internal",
"PrivateIpAddress": "172.31.6.239"
}
]
EOF

(使代码的格式/缩进与OP的格式/缩进相匹配,以简化视觉比较)

输出为:
"ip-172-31-6-209.us-west-2.compute.internal"
"ip-172-31-6-229.us-west-2.compute.internal"

“在我看来就像伏都教。”

使用 | IN("a","b","c")
更新:已经16个月了,我终于学会了如何使用 IN函数。这是一个演示,将产生与上面相同的结果。
cat > filter.jq <<EOF
# Either of these work in jq < v1.5, but I've commented them out since I'm using v1.6
# def IN(s): first( if (s == .) then true else empty end ) // false;
# def IN(s): first(select(s == .)) // false;

.[] | select(.PrivateIpAddress | IN("172.31.6.209","172.31.6.229")) | .PrivateDnsName
EOF

jq -f filter.jq <<EOF
[
{
"PrivateDnsName": "ip-172-31-6-209.us-west-2.compute.internal",
"PrivateIpAddress": "172.31.6.209"
},
{
"PrivateDnsName": "ip-172-31-6-219.us-west-2.compute.internal",
"PrivateIpAddress": "172.31.6.219"
},
{
"PrivateDnsName": "ip-172-31-6-229.us-west-2.compute.internal",
"PrivateIpAddress": "172.31.6.229"
},
{
"PrivateDnsName": "ip-172-31-6-239.us-west-2.compute.internal",
"PrivateIpAddress": "172.31.6.239"
}
]
EOF

关于arrays - jq:选择列表中的.attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50750688/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com