Home > Enterprise >  need to extract specific string with JQ
need to extract specific string with JQ

Time:10-12

I have a JSON file (see below) and with JQ I need to extract the resourceName value for value = [email protected]

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("[email protected]"; "i")) | .resourceName' file.json

{
  "connections": [
    {
      "resourceName": "name_1",
      "etag": "123456789",
      "emailAddresses": [
        {
          "metadata": {
            "primary": true,
            "source": {
              "type": "CONTACT",
              "id": "123456"
            }
          },
          "value": "[email protected]",
        }
      ]
    },
    {
      "resourceName": "name_2",
      "etag": "987654321",
      "emailAddresses": [
        {
          "metadata": {
            "primary": true,
            "source": {
              "type": "CONTACT",
              "id": "654321"
            },
            "sourcePrimary": true
          },
          "value": "[email protected]"
        }
      ]
    }
  ],
  "totalPeople": 187,
  "totalItems": 187
}

CodePudding user response:

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

jq '.connections[] | . as $parent | .emailAddresses // empty | .[] | select(.value == "[email protected]") | $parent.resourceName' file.json

CodePudding user response:

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

.connections[] | select(any(.emailAddresses[];.value == "[email protected]")).resourceName
  • Related