Extract a field if it is accompanied by specific key-value pairs

Viewed 55
//test.json
{
"RED":
  [
    {
      "attr1": "aaaa",
      "attr2": "bbbb",
      "attr3": "cccc"
    },
    {
      "attr1": "aaaa",
      "attr2": "dddd",
      "attr3": "eeee"
    }
  ],
"WHITE":
  [
    {
      "attr1": "aaaa",
      "attr2": "bbbb",
      "attr3": "cccc"
    },
    {
      "attr1": "aaaa",
      "attr2": "dddd",
      "attr3": "eeee"
    }
  ]
}

I want to get a value that meets (key=RED && attr1="aaaa" && attr2="bbbb")

So I have written jq command like this :

jq -r 'with_entries(select([.key] | inside(["RED"]))) | .[] | .[] | select(.attr1=="aaaa") | select(.attr2=="bbbb") | .attr3' test.json

this command works well. but I think that command is a little long. How can I shorten the command without reducing readability? (* This is my first time using JQ)

1 Answers

You don't need with_entries or multiple selects there. The following program does exactly the same thing and is way shorter.

.RED[] | select(.attr1 == "aaaa" and .attr2 == "bbbb") .attr3
Related