how to use jq to filter an object based on it's key:value pair?

Viewed 184

Assuming this is the input

>echo '{"A": {"x": 1}, "B": {"x":2}, "C":{"x":3}}' | jq '.'
{
  "A": {
    "x": 1
  },
  "B": {
    "x": 2
  },
  "C": {
    "x": 3
  }
}

I would like to get the return object of "x" == 2. The only way i know of how to achieve that is thru this

>echo '{"A": {"x": 1}, "B": {"x":2}, "C":{"x":3}}' | jq '.[] | select(.x==2)'
{
  "x": 2
}

Is there a way to have jq return me like this instead?

{
  "B": {
    "x": 2
  },
}

 
2 Answers

You can also use map_values :

map_values(select(.x == 2))
with_entries(select(.value.x == 2))
Related