简体   繁体   中英

How to select items in JQ based on values in array

I have a json file with data like this:

{ 
  "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?

So the output would be something like:

{
"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:

{
  "members": [
    {
      "id": 10,
      "name": "First"
    },
    {
      "id": 14,
      "name": "Third"
    }
  ]
}

And if you need more flexibility how your ids are matched:

.data.all
| .live.online as $online
| { members: .members | map(select(.id as $id | $online | any(. == $id))) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM