1

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.

peak
  • 105,803
  • 17
  • 152
  • 177
Christopher Shroba
  • 7,006
  • 8
  • 40
  • 68

1 Answers1

1

You could easily define your myFilter using reduce:

def myFilter($keys):
  . as $in
  | reduce $keys[] as $k (null; . + {($k): $in[$k]} );

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:

jq -n '{name: "Chris", age: 25, city: "Chicago"} | {name, age}'

If any of the keys cannot be specified in this abbreviated format, simply double-quote them.

peak
  • 105,803
  • 17
  • 152
  • 177