How to store a JSON in a variable and use it in the request body?

Hi,

I want to run a collection with specific test data, but restore the data from before my collection run afterwards.

My idea to achieve this is so far:

  1. Execute a GET request to retrieve the currently available data. Format: JSON
  2. Store that data in an environmentvariable
  3. Run collection that includes overriding the original data with PUT request containing my test data.
  4. Restore the original data from the environmentvariable

However this doesn’t seem to work.

Approach #1:
I used the code from a tutorial to store the data:

let response = pm.response.json();
let savedData = response;
pm.environment.set(“savedData”, savedData );

I checked data saved in the environment variable and it looks fine.

But I cannot pass the data to the body. I tried this in the body:

{{“savedData”}}

Approach #2:
I only stored the values of the data, but not the whole JSON:

let response = pm.response.json();
let savedData = response.values;
pm.environment.set(“savedData”, savedData );

And then trying this in the body:

{
“myData” : [{{“savedData”}}]
}

Doesn’t work either.

Any idea how to solve this problem?

1 Like

@Myxlplyx

Try {{savedData}} instead of {{"savedData"}}. :cowboy_hat_face:

Thanks for your answer!

However if I try:
{
“myData”: [{{savedData}}]
}

I get the following error message:

Can not deserialize instance of com.xxx.xxx.xxx.xxx.xx.xxx.SavedData out of START_ARRAY token
at [Source: io.undertow.servlet.spec.ServletInputStreamImpl@39123303; line: 2, column: 24] (through reference chain: com.xxx.xxx.xxx.xxx.xx.xxx.xxxx.SavedDataMap[“savedData”]->java.util.ArrayList[0])

Any idea?

@Myxlplyx - So to solve your problem.

  1. In the test script of your GET request, you can put this down:
let response = pm.response.json(),
    savedData = JSON.stringify(response);

pm.environment.set("savedData", savedData);

You need to store the data in stringified format.

  1. In the body of the requests where you want to use this savedData you can simply put it like so:
    Make the body as ‘Raw’ and the type as ‘JSON’:

image

Put the following as the raw data:

{
   "myData": [{{savedData}}]
}

Run the request and you can see the following in the Postman Console

4 Likes

Hi sivcan,
thanks for your answer.

I also found a solution just a few hours ago before I saw your response.

This thread gave me the needed hint:

Here spefically this:

postman.setEnvironmentVariable(“deviceMapping”, responseBody);
//variables need to be strings

After understanding that responseBody stores the whole response body as a string, the solution was as easy as:

  1. In the GET request save the whole JSON response body to an environment variable:

postman.setEnvironmentVariable(“savedData”, responseBody);

  1. To pass the JSON data into a consecutive request just put the following as raw data:

{{savedData}}

That’s it :slight_smile:

@sivcan, thank you for the clarity here. I couldn’t find this info anywhere else!

I have a response of a API which looks like this on a GET - GET on API1
[
{
“id”: “emp1”,
“name”: suresh,
“address”: zxr street,
“zip”: 92111,
“city”: “fresno”,
“notes”: “employee of month”

},
{
	"id": "emp2",
    "name": rakesh,
    "address": zxry street,
    "zip": 92122,
    "city": "bakersfield",
    "notes": "hired recently",
}

]

I would like to extract only the city and provided it as a parameter to API 2
API 2 - companies/Co123/employees/3333?city={{cities}}

can anyone please guide me.

The piece of code below will take the first city. If your result is a list:

pm.environment.set("CityId", pm.response.json()[0].city); or
pm.environment.set("CityId", pm.response.json().city); if is just one result.

Then use this variable in your request this way:

API 2 - companies/Co123/employees/3333?city={**{CityId}**}

However, if you want save all cities, you can use push() and pop() methods to append the results in a list and them iterate in other requests.

I’m kinda new here too, but I often do that way!

:sweat_smile:

thanks sandokhan. Thats exactly the difficultly am having.
Do you have an example for multiple results to be chained to the next API?

its straight forward with one city . I am looking for multiple cities going in as input to the next API

1 Like

I’m here to fight the scope pollution fight :triumph:

If you don’t want to pollute your environment, please use collection variables when sharing data between requests in a collection! It’s the exact same thing but just pm.collectionVariables.set() instead of pm.environment.set()

1 Like

In the first request, on test I’ll put this code:

let Cities = JSON.parse(responseBody),
CityIds = _.map(body, (city) => city.id);

// Store all the Cities Ids in the environment variable
pm.environment.set('CityIdsList', JSON.stringify(CityIds));

// Store the next index of the array for City ids
pm.environment.set('nextIndex', 0);

// Store the active City ID 
pm.environment.set('activeCityId', CityIds[0]);

Then, on the second request I’ll use this one:

let CityIds = JSON.parse(pm.environment.get('CityIdsList')),
    nextIndex = parseInt(pm.environment.get('nextIndex')) + 1;

if (CityIds.length === nextIndex) {
    pm.environment.set('nextIndex', 0);
    pm.environment.set('activeCityId', CityIds[0]);

    postman.setNextRequest(null);
} else {
    let activeRODID = CityIds[nextIndex];
    pm.environment.set('nextIndex', nextIndex);
    pm.environment.set('activeCityId', activeCityId);
    postman.setNextRequest("Second Request");
}

Perhaps there is a more efficient way to do it, but this will work.