Postman test - How to manipulate environment variable JSON values

Here is my requirement: Appreciate any pointers:

  1. Make a post request - Done
  2. Save the portion of the JSON response into env variable (var name = envbody) - Done
  3. Read the env variable (envbody) to get JSON schema with values - Done
  4. Read csv file has 100 rows with query and locale - Done
  5. envbody environment variable has Json object stringified - Done
  6. envbody has json with one of attribute name called query.
    Replace query attribute value of envbody with csv iteration data query value
  7. Repeat till end of csv file

I have done 1-5. How do I manipulate / insert value into envbody variable
Here is the code snippet


 var resultObject = JSON.parse(responseBody);
 var searchBody = resultObject.searchPostBody;
 var searchBodyStr= JSON.stringify(searchBody);
 postman.setEnvironmentVariable("searchPostBody", searchBodyStr);

Reading csv file - No issues

Need to replace one of the attribute value in searchPostBody env variable using csv iteration data

For example, in this case, searchPostBody has a Json object with one of the attribute names is query (q).

I need to replace the value of “q” with the value which is read from the csv file.

{
    "expe": "xxx",
    "q": "",
    "limit": 10,
    "locale": "en_US",
    "timeout": 10000
}

Thanks, Raje

Hey @rjayaram

If I had this value saved as an environment variable:

{
    "expe": "xxx",
    "q": "",
    "limit": 10,
    "locale": "en_US",
    "timeout": 10000
}

I would change the q value using pm.iterationData.get('query') by adding this to the Pre-request Script:

let searchPostBody = JSON.parse(pm.environment.get('searchPostBody'))

searchPostBody.q = pm.iterationData.get('query');

pm.environment.set('searchPostBody', JSON.stringify(searchPostBody))

The set the Request Body to:

{{searchPostBody}}

In the Runner, I would select my data file (I’ve used a JSON file here):

[
	{
		"query": "one"
	},
	{
		"query": "two"
	},
	{
		"query": "three"
	},	
	{
		"query": "four"
	},	
	{
		"query": "five"
	}
]

When this is run, it will grab the environment variable value, set the q property to the iterationData value before storing that back into the environment variable again. The POST request will be sent with the new value in the q property.


Hi @dannydainton

Thanks for your suggestion. It worked perfectly.

Appreciate your help.

Thaks, Raje

2 Likes