Search code examples
jsonjmespath

How to use JMESPath to filter array of object based on contains of value in subproperty arrary


How use JMESPath to filter nodes that possess email receivers with exact email? I have JSON object:

   [     
     {
        "test":1,
        "emailReceivers": [
          {
            "emailAddress": "a1@abc.com",
          }
        ]
      },
      {
        "test":2,
        "emailReceivers": [
          {
            "emailAddress": "a2@abc.com",
          },
          {
            "emailAddress": "a3@abc.com",
          }
        ]
      }
    ]

I would like to get node after filtering by elememailReceivers that contains a1@abc.com:

     {
        "test":1,
        "emailReceivers": [
          {
            "emailAddress": "a1@abc.com",
          }
        ]
      }

I was trying to use documentation https://jmespath.org/ and examples but I failed.


Solution

  • You can indeed use contains on a filter and ask sub-keys containing a certain value.

    With the query

    [?contains(emailReceivers[].emailAddress, 'a1@abc.com')]
    

    This will give:

    [
      {
        "test": 1,
        "emailReceivers": [
          {
            "emailAddress": "a1@abc.com"
          }
        ]
      }
    ]
    

    On your example array:

    [     
      {
        "test":1,
        "emailReceivers": [
          {
            "emailAddress": "a1@abc.com"
          }
        ]
      },
      {
        "test":2,
        "emailReceivers": [
          {
            "emailAddress": "a2@abc.com"
          },
          {
            "emailAddress": "a3@abc.com"
          }
        ]
      }
    ]