I'm trying to define some custom filter functions and one thing I need to be able to do is pass a list of strings to a filter and get the corresponding values of the input object. For example:
jq -n '{name: "Chris", age: 25, city: "Chicago"} | myFilter(["name", "age"])'
should return:
{"name": "Chris", "age": 25}.
I know I can use .[some_string] to dynamically get a value on an object for a specific string key, but I don't know how to utilize this for multiple string keys. I think the problem I'm running into is that jq by default iterates over objects streamed into a filter, but doesn't give a way to iterate over an argument to that filter, even if I use def myFilter($var) syntax that the manual recommends for value-argument behavior.
You could easily define your
myFilterusingreduce:More interestingly, if you're willing to modify your "Query By Example" requirements slightly, you can simply specify the keys of interest in braces, as illustrated by this example:
If any of the keys cannot be specified in this abbreviated format, simply double-quote them.