11

Given a document like this:

[
  {
    "KVs" : [
      {
        "Key": "animal",
        "Value": "lion"
      },
      {
        "Key": "mascot",
        "Value": "lion"
      }
    ],
    "name": "roger"
  },
  {
    "KVs" : [
      {
        "Key": "animal",
        "Value": "zebra"
      },
      {
        "Key": "mascot",
        "Value": "lion"
      }
    ],
    "name": "linda"
  }
]

I want to use jq to select only those elements of the top array that contain the KV pair animal == "lion".

The output for the above JSON document should be:

{
  "KVs" : [
    {
      "Key": "animal",
      "Value": "lion"
    },
    {
      "Key": "mascot",
      "Value": "lion"
    }
  ],
  "name": "roger"
}

Can't figure out how to accomplish this with select(). I know how to use it to select based on one specific field. e.g. by key name: .[] | select(.KVs[].Key == "animal"), right? But how do I tell it to match the same KV object on two fields (Key & Value)?

1 Answer 1

14

NM, solved it with the help of jqplay and some trial and error.

This is the solution: .[] | select(.KVs[] | .Key == "animal" and .Value == "lion")

(jqplay permalink)

Sign up to request clarification or add additional context in comments.

4 Comments

It doesn't matter here, since only one inner object matches, but in general you might prefer to use any. Compare .[]|select(.KVs|any(.Value=="lion")) and .[]|select(.KVs[]|.Value=="lion")
Interesting. But what is the difference, actually? Why would I prefer to use any?
Compare the number of results in both cases.
Note to return the value of the name element from the result (ie "roger"), use .[] | select(.KVs[] | .Key == "animal" and .Value == "lion") | .name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.