Rizvan Ferdous
Rizvan Ferdous

Reputation: 69

jsonPath - how to filter results by matching substring

I have a structure like this:

{"payload": {

    "Item1": {
      "property1": "Sunday",
      "property2": "suffering_8890"
    },

    "Item2": {
      "property1": "Monday",
      "property2": "misery_0776"
    },

    "Item3": {
      "property1": "Tuesday",
      "property2": "pain_6756"
    }
  }
}

I need the property2 value that contains a certain sub-string (i.e- "misery"). Ultimately I just need the 4-digit code, but even getting the full value will work. I am able to get a list of all the property2 values by using:

$..property2

This returns:

Result[0] = suffering_8890
Result[1] = misery_0776
Result[2] = pain_6756

How do I filter it so that it only gives me the result containing the substring "misery"?

Upvotes: 4

Views: 13566

Answers (2)

Dmitri T
Dmitri T

Reputation: 167992

With regards to full value you can use a Filter Operator like:

$..[?(@.property2 =~ /misery.*?/i)].property2

Demo:

enter image description here

You can extract the 4-digit value out of the variable using Regular Expression Extractor


If you want to do this in one shot:

  1. Add JSR223 PostProcessor as a child of the request which returns above JSON
  2. Put the following code into "Script" area

    vars.put('misery', ((com.jayway.jsonpath.JsonPath.read(prev.getResponseDataAsString(), '$..[?(@.property2 =~ /misery.*?/i)].property2').get(0) =~ ('(\\d+)'))[0][1]))
    
  3. Refer the extracted value as ${misery} where required

More information: Apache Groovy - Why and How You Should Use It

Upvotes: 6

Amol Chavan
Amol Chavan

Reputation: 3970

You can use a regular expression extractor as well for the mentioned scenario to fetch the four-digit as below

property2": "misery_(.*)"

This will help you to save the four-digit code in JMeter variables right away. If you insist you to find out the required value from JSON using jsonpath, you can use JSON filter as below :-

$..[?(@.property2.indexOf('misery')>=0)]..property2

Upvotes: 0

Related Questions