[英]How to select items in JQ based on values in array
I have a json file with data like this:我有一个 json 文件,其中包含如下数据:
{
"data": {
"all": {
"members": [
{
"id": 10,
"name": "First"
},
{
"id": 12,
"name": "Second"
},
{
"id": 14,
"name": "Third"
}
],
"live": {
"online": [
10,
14
]
}
}
}
}
How can I use jq to select and show only the JSON values in data.all.members
that have their id
in data.all.live.online
array?如何将 jq 用于 select 并仅显示 data.all.members 中的
data.all.members
值,其id
在data.all.live.online
数组中?
So the output would be something like:所以 output 将类似于:
{
"members": [
{
"id": 10,
"name": "First"
},
{
"id": 14,
"name": "Third"
}
]
}
One way:单程:
jq '.data.all
| .live.online as $online
| {members}
| .members[] |= select(.id | IN($online[]))
' data.json
Here's a solution that should be fairly easy to understand:这是一个应该相当容易理解的解决方案:
.data.all
| .live.online as $online
| { members: .members | map(select([.id] | inside($online))) }
Output: Output:
{
"members": [
{
"id": 10,
"name": "First"
},
{
"id": 14,
"name": "Third"
}
]
}
And if you need more flexibility how your ids are matched:如果您需要更大的灵活性,您的 id 如何匹配:
.data.all
| .live.online as $online
| { members: .members | map(select(.id as $id | $online | any(. == $id))) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.