Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering objects in jq by existence of nested array values

Tags:

jq

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)?

like image 320
Assaf Lavie Avatar asked Dec 19 '17 12:12

Assaf Lavie


1 Answers

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)

like image 82
Assaf Lavie Avatar answered Oct 25 '22 12:10

Assaf Lavie