jq: selecting a subset of keys from an object

Jon picture Jon · Apr 8, 2015 · Viewed 19.7k times · Source

Given an input json string of keys from an array, return an object with only the entries that had keys in the original object and in the input array.

I have a solution but I think that it isn't elegant ({($k):$input[$k]} feels especially clunky...) and that this is a chance for me to learn.

jq -n '{"1":"a","2":"b","3":"c"}'   \
    | jq --arg keys '["1","3","4"]' \
    '. as $input 
     | ( $keys | fromjson )
     | map( . as $k
          | $input
          | select(has($k))
          | {($k):$input[$k]}
          )
     | add'

Any ideas how to clean this up?

I feel like Extracting selected properties from a nested JSON object with jq is a good starting place but i cannot get it to work.

Answer

user5672998 picture user5672998 · Sep 19, 2017

solution with inside check:

jq 'with_entries(select([.key] | inside(["key1", "key2"])))'