Encountering a problem when attempting to send a JSON object with the BeanShell PreProcessor

I need to send a JSON Object to the HTTP Request body in JMeter using the BeanShell PreProcessor. The JSON object is modeled using java code with some business logic. I have created a BeanShell PreProcessor and written the java code below,

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

    String key="testKey";
    int lastID=5548;
    int totalCount=198;
    JSONObject obj1 = new JSONObject();
    JSONArray obj2 = new JSONArray();
    for (int i=1;i<=totalCount;i++)
    {
        JSONObject item = new JSONObject();
        item.put("taskId", Integer.toString(lastID+i));
        item.put("taskOrder",1);
        item.put("snapshotTemplateKey",key);
        obj2.put(item);
        obj1.put("changeControlTasks", obj2);
        obj1.put("ccName","Eleven" );
        obj1.put("snapshotTemplateKey",key);
    }
    log.info(obj1);
    vars.putObject("jsonData",obj1);

The data from the above code is being fetched in the HTTP request body as shown below,

${jsonData}

When running this, an error is encountered:

Request :

POST data:
${jsonData}

Error in the logs:

2017/08/06 07:27:10 ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval
Sourced file: inline evaluation of: ``import org.json.JSONArray; import org.json.JSONException; 
import org.json.JSONOb . . . '' : Error in method invocation: Method info(  ) not found in class'org.apache.log.Logger'

If anyone can provide insights on what could be the issue with the code above and how to resolve it, it would be greatly appreciated.

any suggestions or solutions will also be appreciated.

Answer №1

obj2 contains the data. Utilize obj2 in place of obj1:

 vars.store("jsonData", obj2);

To log, convert to a string:

 log.message(obj1.toString());

Answer №2

  1. Your Beanshell script may encounter an issue at this line:

    log.info(obj1); 
    

    as it is unable to print a JSON Object into the log.

  2. If you attempt to work around this issue with your HTTP Request sampler, you will face a similar obstacle: JMeter requires a String as body data and cannot accept a JSON Object.
  3. Consider utilizing JSR223 PreProcessor with Groovy language instead of Beanshell for high thread load tests. Groovy offers built-in JSON support and superior performance due to the efficient compilation and caching of scripts. Here is an example of how you can rewrite your script in Groovy:

    import groovy.json.JsonBuilder
    
    def key = 'testKey'
    def lastID = 5548
    def totalCount = 198
    
    JsonBuilder builder = new JsonBuilder()
    
    def array = []
    1.upto(totalCount, {
        def taskId = (lastID + "${it}".toInteger())
        array << [getKey: { key }, getTaskId: { taskId }, getTaskOrder: { 1 }]
    
    })
    
    builder(
            {
                changeControlTasks array.collect() {
                    [
                            "snapshotTemplateKey": it.getKey(),
                            "taskId"             : it.getTaskId(),
                            "taskOrder"          : it.getTaskOrder()
                    ]
                }
                snapshotTemplateKey "testKey"
                ccName "Eleven"
            }
    )
    
    vars.put('jsonData', builder.toPrettyString())
    

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Interact with visible elements by automating mouse clicks with puppeteer

When attempting to click on various elements within a page, my goal is to do so only if they are visible. While achieving this in selenium with the is_displayed method was simple, I have struggled to find a similar approach in puppeteer. I attempted to imp ...

The json_encode() function returned a JSON that is not valid

In my PHP file (although more complex, even with the simplest code it fails), I have: <?php $salida = array(1,2,3,4,5); echo json_encode($salida); ?> The response received is: [1,2,3,4,5] While this appears valid, it's actually not. When pas ...

Strategies for accessing array elements based on category

I am currently working with an array of diverse products var productList = [ { id: '1', category: 'todos', menuName: 'Empanada de Carne, Pollo o Mixta + Café 8oz.', menuPrice: '9.99&a ...

The instance does not have a definition for the property or method "names" that is being referenced during rendering

Currently, I'm working on developing a CRUD application using Vue.js and Firebase. However, I've encountered an error that I can't seem to resolve: [Vue warn]: Property or method "names" is not defined on the instance but referenced during r ...

HTML element DIV positioned above the iframe

I am looking for a way to automatically place a "PLAY" div above each iframe instead of doing it manually. I have successfully done it manually but I'm not sure how to achieve the same result with a script or using CSS. Below is my HTML markup: < ...

I am interested in utilizing a variable's value as an ID within a jQuery function

When working with jQuery, I often use a variable to store values. For example: var x = "ID1"; To utilize the value of this variable as an ID in my jQuery functions, I simply concatenate it as shown below: $('#' + ID1).val(); Thank you for you ...

Obtain the value stored in the variable named "data"

I'm trying to calculate the sum of data values using jQuery, similar to this example: { label: "Beginner", data: 2}, { label: "Advanced", data: 12}, { label: "Expert", data: 22}, and then add them together. Like so: var sum = data1+data2+dat ...

Does it typically occur to experience a brief pause following the execution of .innerHTML = xmlhttp.responseText;?

Is it common to experience a brief delay after setting the innerHTML with xmlhttp.responseText? Approximately 1 second delay occurs after xmlhttp.readyState reaches 4. This issue is observed when using Firefox 3.0.10. ...

Leverage Jasmine for testing a jQuery plugin

I'm currently utilizing the angular-minicolors library () within an angular controller: angular.element("myelement").minicolors({ position: 'top left', change: function() { //custom code to run upon color change } }) Wh ...

Having trouble locating a tag when converting an object to an array in Android using JSONArray

I am currently working on retrieving data from an API using JSON in an Android application. After successfully downloading the information, I need to store it in a JSONArray with the tag "Categories" for display in a ListView. Below is the code snippet I a ...

Utilize esbuild to monitor for any modifications, recompile the code, and automatically restart the express server

In my endeavor to develop a basic SSR-powered project using express + react, I find the need to monitor frontend and backend scripts concurrently in the development process. The primary objective is to utilize express routes in directing to react page com ...

Storing a JSON response in a variable

I need assistance with using the Google Geocoder API to obtain the longitude and latitude of an address for a mapping application. How can I retrieve data from a geocode request, like this example: "http://maps.googleapis.com/maps/api/geocode/json?address ...

Removing an element from an object using ng-model when its value is empty is a standard practice

Utilizing the $resource service to access and modify resources on my API has been a challenge. An issue arises when the ng-model-bound object's value is set to empty - the bound element is removed from the object. This results in the missing element ...

Clicking on a checkbox within an HTML table that incorporates handlebar and Express.js

My situation involves a HTML table within a form that is being populated with Handlebars. I need to be able to select certain rows in the table using checkboxes, and upon form submission through a POST request in an Express.js framework, I require the JSON ...

Managing and updating arrays in VueJS2: Conditionally push new items and update only if their properties have changed

I am currently facing an issue with my form where each time a user updates a value in an input field, a new array element is created and added to the form results. I'm looking for a way to update the properties of the existing array element without cr ...

Improving React Efficiency: Should You Utilize Memoization of Axios GET Request Using useMemo or useCallback?

My Objective: I am currently working on a sizable function named getUnitedStatesCases, which involves making an Axios GET Request and performing various operations with the received data. I have already implemented it within a useEffect hook upon componen ...

Create a dynamic menu dropdown with absolute positioning using React

I recently made the transition to React and now I am in the process of converting my old vanillaJS website into ReactJS. One issue I am facing is with a button that is supposed to trigger the opening of a dropdown menu. <button type="button&qu ...

The Cordova minification tool fails to compress files within the browser platform

I recently installed the cordova-minify plugin to compress the javascript code in my Cordova app. When I tried running the command: cordova build browser An output message appears: cordova-minify STARTING - minifying your js, css, html, and images. ...

Exploring the global data subfolder in Eleventy / 11ty with iterative methods

I am working with Eleventy and have set up a subfolder called yummy in my global data folder. This subfolder contains the following files: \src\_data\yummy\drinks.json \src\_data\yummy\food.json When I use {{ yummy ...

Parcel-Bundler is unable to resolve critical security issues

I recently followed a tutorial by Kevin Powell on SASS and Parcel through YouTube. I was able to successfully set up the SASS part and get the Parcel bundler working smoothly on one project, so everything seemed to be going well at that point. However, to ...