Save response to variable in Thunder Client

1.4k Views Asked by At

I want to save the response from two API calls but not sure how to do it in Thunder client, Postman is working fine.

var jsonDataResponse = JSON.parse(responseBody);
pm.environment.set("tin", jsonDataResponse.replace(/\s/g, ''));

One. https://generator.avris.it/api/DE/tin gives something like "21 348 504 760" and then in Postman I have this

postman image 1

But in Thunder, I have no idea how can I do that

thunder try

And I want to just the number without spaces

Two. I have this in Postman but no clue how made this in Thunder

let jsonData = JSON.parse(responseBody);
positionstring=""+jsonData.positions;

pwdstring=positionstring.replace(new RegExp(",", "g"), "");
positionstring=positionstring.replace(new RegExp(",", "g"), "\",\"");

positionstring ="\[\""+positionstring+"\"\]";
postman.setEnvironmentVariable("positions", positionstring);
postman.setEnvironmentVariable("pwd", pwdstring);

postman image 2

I tried the first one but only I get to save it to a tin variable with literally the function I want to replace(" ", "") when should be 21348504760

2

There are 2 best solutions below

0
user3717796 On BEST ANSWER

I just solved it, here it is Create a JavaScript file with the function like this

function positions() {  

// Parse the JSON text into an object
const jsonObject = tc.response.json;

// Create the positions array using the values from the JSON object
const twostring = jsonObject.positions.map(value => value);

// Create the pwd variable
const onestring= jsonObject.positions.map(Number).join('');

tc.setVar("onestring",onestring);   
tc.setVar("twostring",twostring);

}
module.exports = [positions]

Then in the request go to Tests tab, Post Request Script and select the function, in this case "positions".

(In order functions appear there, in collection options file should be listed in Script Files)

2
Bench Vue On

Not necessary to convert JSON

The responseBody just string. So you just need to remove space from string of responseBody. And remove the Double Quote mark. It will be a string, then convert into Number()

Then assign the environment variable into tin.

const tin_string = responseBody.replace(/\s/g, '').replace(/"/g,'');

tin_number = Number(tin_string)

pm.environment.set("tin",tin_number)

If you want to debug the handling of your code in Tests tab, the console.log() is useful.

This is an example of debug.

console.log(responseBody)

const tin_string = responseBody.replace(/\s/g, '').replace(/"/g,'');
console.log(tin_string)

tin_number = Number(tin_string)
console.log(tin_number)

pm.environment.set("tin", tin_number)

enter image description here

Assigned environment variable tin

enter image description here