Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq Filter on sub object value

Tags:

json

jq

I have a json file people.json:

{
  "Joe" : {"Job" : "Clown", "Age" : 22},
  "Sally" : {"Job" : "Programmer", "Age" : 32},
  "Anne" : {"Job" : "Clown", "Age" : 29}
}

I would like to select everyone who is a Clown. My output should look like this:

{
  "Joe" : {"Job" : "Clown", "Age" : 22},
  "Anne" : {"Job" : "Clown", "Age" : 29}
}

I have tried the .. operator as in

cat people.json | jq '. | map(select(.Job == "Clown"))'

But it seems to match Joe and Anne at multiple levels and produces more output then I want. Any ideas? Thanks.

like image 868
Christopher Helck Avatar asked Feb 19 '15 19:02

Christopher Helck


2 Answers

use with_entries to convert to/from an intermediate format that represents that data as an array of objects with key and value elements:

cat people.json | jq 'with_entries(select(.value.Job == "Clown"))'

as per the docs here: http://stedolan.github.io/jq/manual/

like image 190
Hans Z. Avatar answered Oct 14 '22 22:10

Hans Z.


Here is a solution using reduce

  . as $v
| reduce keys[] as $k (
    {};
    if $v[$k].Job == "Clown" then .[$k] = $v[$k] else . end
  )
like image 37
jq170727 Avatar answered Oct 14 '22 22:10

jq170727