Search code examples
jsontestingpostmanthunderclient

Save response to variable in Thunder Client


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


Solution

  • 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)