Dyptorden
Dyptorden

Reputation: 1197

Json Path Extractor expression to get values when substring is present

I am using JMeter's "JSON Extractor" and I try to get all "recipients" arrays from the following response, if one of their elements contains a specific string. To be more exact, I have the following JSON response:

    {
        "size": "12",
        "sender": "<[email protected]>",
        "recipients": [
            "<[email protected]>",
            "<[email protected]>",
            "<[email protected]>"
        ],
        "subject": "super mail",
        "id": 1
    },
    {
        "size": "35",
        "sender": "<[email protected]>",
        "recipients": [
            "<[email protected]>",
            "<[email protected]>"
        ],
        "subject": "super subject",
        "id": 2
    },
    {
        "size": "41",
        "sender": "<[email protected]>",
        "recipients": [
            "<[email protected]>",
            "<[email protected]>",
            "<[email protected]>"
        ],
        "subject": "nothing special",
        "id": 3
    }
]

And I want to find all the recipients that have at least one element containing the substring "mar". The expression that gets the closest answer to what I need is:

$..*.[?(@.recipients.* contains '<[email protected]>')].recipients

This will return :

Result[0]=["<[email protected]>","<[email protected]>","<[email protected]>"]

How can I change the filter so that I get:

Result[0]=["<[email protected]>","<[email protected]>","<[email protected]>"]
Result[1]=["<[email protected]>","<[email protected]>","<[email protected]>"]

as both "marry" and "mariah" contain the substring "mar".

$..*.[?(@.recipients.* contains 'mar')].recipients doesn't work as "contains" refers most probably to an element of the arrays and not to a substring of an element.

Thank you,

Upvotes: 0

Views: 522

Answers (1)

Dmitri T
Dmitri T

Reputation: 168157

I don't think you can use JSON Extractor for this, your requirement could be implemented using JSON JMESPath Extractor, however it's implemented in such a weird way that it doesn't return a valid JSON in case of arrays and it makes any advanced usage impossible or at least inconvenient resulting in coming up with a boilerplate transformations and mappings.

The fastest and the easiest option would be implementing the filtering using JSR223 Post Processor and Groovy language functions.

Example code:

def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())

response.recipients.findAll { recipient -> recipient.findAll { it.contains('mar') } }.eachWithIndex { result, index ->
    def emails = new groovy.json.JsonBuilder(result).toString()
    log.info(emails)
    vars.put('myVar_' + (index + 1), emails)
}

Demo:

enter image description here

More information:

Upvotes: 1

Related Questions