Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq: selecting a subset of keys from an object

Tags:

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.

like image 321
Jon Avatar asked Apr 08 '15 14:04

Jon


People also ask

Does jq use JSONPath?

jp is a JSON processor for the command line using JSONPath (aka "a simpler jq, and with JSONPath").

What is a jq filter?

A jq program is a "filter": it takes an input, and produces an output. There are a lot of builtin filters for extracting a particular field of an object, or converting a number to a string, or various other standard tasks.

What is jq slurp?

The slurp option ( -s ) changes the input to the jq program. It reads all the input values and build an array for the query input. Using with the raw input option ( -R ) means reading the entire input as a string. The inputs function is a special stream that emits the remaining JSON values given to the jq program.


2 Answers

solution with inside check:

jq 'with_entries(select([.key] | inside(["key1", "key2"])))' 
like image 67
user5672998 Avatar answered Sep 17 '22 12:09

user5672998


You can use this filter:

with_entries(     select(         .key as $k | any($keys | fromjson[]; . == $k)     ) ) 
like image 20
Jeff Mercado Avatar answered Sep 16 '22 12:09

Jeff Mercado