0

From a JSON response of the format below,

{"data":[{"id":"xxx","data":{"A":"111","B":"222","C":"333"}},{"id":"yyy","data":{"A":"111","B":"222","C":"333"}}]

I need to fetch only IDs and pass it in the next request as a list like

{"data":["xxx","yyy"]}

I was able to fetch all these IDs using a Regular Expression Extractor with the following values.

Reference Name = data ; 
Regex = "id":"(.+?)" ;
Template = $1$ ;
Match No = -1 ;

The IDs retrieved are in the following format.

data_1 = xxx
data_2 = yyy

But the IDs could be a lot, so I need an efficient way where I can use just one variable instead of using {"data":["data_1","data_2"]} and so on.

0

You can build a single variable out of these data_1, data_2, etc. as follows:

  1. Add Beanshell PostProcessor after your Regular Expression Extractor
  2. Put the following code into the PostProcessor's "Script" area:

    StringBuilder dataBuilder = new StringBuilder();
    dataBuilder.append("{\"data\":[");
    
    int ids = Integer.parseInt(vars.get("data_matchNr"));
    for (int i = 1; i <= ids; i++) {
    
        dataBuilder.append("\"").append(vars.get("data_" + i)).append("\"");
        if (i < ids) {
            dataBuilder.append(",");
        }
    
    }
    
    dataBuilder.append("]}");
    
    vars.put("data", dataBuilder.toString());
    

Above code will concatenate all the variables prefixed with data_ coming from the Regular Expression Extractor into a single JSON array. You can refer the resulting value as ${data} where required.

References:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.