0

I have a list of values that I want to select by in my JQ. That is, my JSON looks something like this:

[
    {
        "id": "a"
    },
    {
        "id": "b"
    },
    {
        "id": "z"
    }
]

My list of values is something like a b c. This list is stored as a scalar variable in bash (not hardcoded). How can I select the corresponding objects from the JSON from this list of values?

I have seen other questions about using a value to select something in a JQ query, but before this I had not seen an example of selecting in JQ based on multiple values. e.g. Select JSON where they're in a given list of values.

Forumpy
  • 305
  • 1
  • 3
  • 13
  • Does this answer your question? [Select objects based on value of variable in object using jq](https://stackoverflow.com/questions/18592173/select-objects-based-on-value-of-variable-in-object-using-jq) – Léa Gris Jun 02 '21 at 15:22

1 Answers1

5

Pass the list of ids to JQ using the --arg directive, split it into an array there and keep that in a variable, and test whether an object's id field holds a value that resides in that array using the IN built-in.

var='a b c'
jq --arg ids "$var" '($ids / " ") as $ids
| .[] | select(.id | IN($ids[]))' file
oguz ismail
  • 1
  • 16
  • 47
  • 69