need to extract specific string with JQ

Viewed 176

I have a JSON file (see below) and with JQ I need to extract the resourceName value for value = mail@mail1.com

So in my case, the result should be name_1

Any idea to do that ? Because this does not work :

jq '.connections[] | select(.emailAddresses.value | test("mail@mail1.com"; "i")) | .resourceName' file.json

{
  "connections": [
    {
      "resourceName": "name_1",
      "etag": "123456789",
      "emailAddresses": [
        {
          "metadata": {
            "primary": true,
            "source": {
              "type": "CONTACT",
              "id": "123456"
            }
          },
          "value": "mail@mail1.com",
        }
      ]
    },
    {
      "resourceName": "name_2",
      "etag": "987654321",
      "emailAddresses": [
        {
          "metadata": {
            "primary": true,
            "source": {
              "type": "CONTACT",
              "id": "654321"
            },
            "sourcePrimary": true
          },
          "value": "mail@mail2.com"
        }
      ]
    }
  ],
  "totalPeople": 187,
  "totalItems": 187
}
2 Answers

One solution is to store the parent object while selecting on the child array:

jq '.connections[] | . as $parent | .emailAddresses // empty | .[] | select(.value == "mail@mail1.com") | $parent.resourceName' file.json

emailAddresses is an array. Use any if finding one element that matches will suffice.

.connections[] | select(any(.emailAddresses[];.value == "mail@mail1.com")).resourceName
Related