Home > Enterprise >  JsonPath: filter by two nested arrays
JsonPath: filter by two nested arrays

Time:06-22

I have a pretty simple JSON Document and want to get all emailAddresses that belong to an 'email'-Contact with a specific source of origin.

This is the JSON:

{
  "errors": [
  ],
  "individuals": [
    {
      "contacts": [
        {
          "id": "urn:uuid:fb383908-4c4a-a00e-3cd2-1f9acf3caecf",
          "origins": [
            {
              "source": "sourceA"
            }
          ],
          "type": "eMail",
          "emailAddress": "[email protected]",
          "verificationStatus": "verification denied"
        },
        {
            "id": "urn:uuid:fb383908-4c4a-a00e-3cd2-1f9acf3caecf",
            "origins": [
              {
                "source": "sourceA"
              }
            ],
            "type": "address",
            "verificationStatus": "verification denied"
          }
      ],
      "id": "urn:uuid:cebb2e06-8bcf-8125-2eee-bb04f8965bcd"
    },
    {
        "contacts": [
            {
              "id": "urn:uuid:fb383908-4c4a-a00e-3cd2-aaaaaaaaa",
              "origins": [
                {
                  "source": "sourceB"
                }
              ],
              "type": "eMail",
              "emailAddress": "[email protected]",
              "verificationStatus": "verification denied"
            },
            {
                "id": "urn:uuid:fb383908-4c4a-a00e-3cd2-aaaaaaaaa",
                "origins": [
                  {
                    "source": "sourceB"
                  }
                ],
                "type": "address",
                "verificationStatus": "verification denied"
              }
          ],
          "id": "urn:uuid:cebb2e06-8bcf-8125-2eee-bbbbbbbbbbbb"
    }
]
}

And this is the JsonPath i have come up with:

$..contacts[?(@.type == 'eMail' && @.origins[?(@.source=='sourceA')])].emailAddress

In my mind this should only return one email address, namely [email protected] but i always get both addresses. Where is my mistake?

PS: sorry for the title, i honestly did not know how to phrase this better

CodePudding user response:

Use the index position for origins instead of using nested expressions.

$..contacts[?(@.type == 'eMail' && @.origins[0].source =='sourceA')].emailAddress

If you are using Jayway JsonPath you can use filter operators like contains

$..contacts[?(@.type == 'eMail' && @.origins[*].source contains 'sourceA')].emailAddress

OR in

$..contacts[?(@.type == 'eMail' && 'sourceA' in @.origins[*].source)].emailAddress
  • Related