0

I have a Jmeter (version 4.0) test script where I am using json extractor to fetch an array of strings from the response json using $..Names and storing it in a variable groupOfNames. The various names are stored like groupOfNames_1, groupOfNames_2, groupOfNames_ALL.

I need to make POST call next with body as

{
"name1", "name2", "name3" (--actual values--)
}

How can i achieve this using bean shell preprocessor? groupOfNames_ALL gives me all value but like this.... name1, name2, name3 (without quotes surrounding individual names). Please help. Thanks.

vaibhav misra
  • 135
  • 6
  • 19
  • may help full to you [stack answer for Jason conversion in java](https://stackoverflow.com/questions/5245840/how-to-convert-string-to-jsonobject-in-java?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) – prat22 Apr 09 '18 at 11:40
  • This is not the issue i am facing but thanks. – vaibhav misra Apr 09 '18 at 11:56

2 Answers2

3

Put the below code in your BeanShell PreProcessor:

int matchNr = Integer.parseInt(vars.get("groupOfNames_matchNr"));

for(int i = 1; i <= matchNr; i++){
    String Names = vars.get("groupOfNames_" + i);
    if(i == matchNr){
        vars.put("AllNames", vars.get("AllNames") + "\"" + Names + "\"");
    }
    else if(i == 1){
        vars.put("AllNames","\"" + Names + "\", ");
    }
    else{
        vars.put("AllNames", vars.get("AllNames") + "\"" + Names + "\", ");
    }

Then use the variable ${AllNames} in your post as below:

{
${AllNames}
}
ararar
  • 953
  • 7
  • 19
3

I heard Groovy is the New Black so you can add quotation marks around each of names as simply as:

vars.put('groupOfNames_ALL',vars.get('groupOfNames_ALL').split(',').collect {"\"$it\""  }.join(', '))

Demo:

JMeter Groovy Add Quotation Marks Around Strings

Also as a gentle reminder: JMeter users are encouraged to use JSR223 Test Elements for any form of scripting since JMeter 3.1

Dmitri T
  • 159,985
  • 5
  • 83
  • 133
  • I have to mark your solution as the right answer as it achieved what i wanted in just a single line. Can you explain what collect and $it is doing in your solution? Thanks a lot anyways :) – vaibhav misra Apr 09 '18 at 19:10
  • You're asking for a story while I'm limited to a chapter. It is implicit parameter: http://groovy-lang.org/closures.html – Dmitri T Apr 09 '18 at 19:15
  • i googled a bit after i asked you and got a rough idea. i am not familiar with groovy so couldn't get it. Thanks for providing the link. It helps – vaibhav misra Apr 09 '18 at 19:30
  • @DmitriT thanks for this. have been looking for a couple of hours on how to solve this problem :D – Dymond Mar 28 '20 at 15:46