简体   繁体   中英

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

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
  },
}

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

You can also use map_values:

map_values(select(.x == 2))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM