How to extract POST request field values in other GET tests

I am trying to put the POST request (not Response) into a global variable like this :

let requestJson = pm.request.toJSON();
pm.globals.set(“aRequestAsJson”, requestJson);

then there is another GET request which retrieves a set of data. I want to compare the field values from this GET response to the field values in the request(that I have in global variable above). somehow I am not able to read any value. the global variable value is just shown as object object

var x = pm.globals.get(“aRequestAsJson”)
console.log(" aRequestAsJson in GET as JSON: " + x);
console.log("abbreviatedDays from REquest : " + x.body.abbrDays);

Can I please get some help in reading the request values from global variable? plan is to then compare the values from global variable(request) with the GET response fields in

pm.expect(pm.response.json().getByAbbrDays).not.eql( x.AbbrDays);

I’d modify your scripts slightly.

For saving the request to a global variable:

const requestJson = pm.request.toJSON();
pm.globals.set('aRequestAsJson', JSON.stringify(requestJson));

When loading it back in your test scripts, just make sure you parse it back into a json object:

const x = JSON.parse(pm.globals.get('aRequestAsJson'));

Thank You Allen,

I tried this : const requestJson = pm.request.toJSON();
pm.globals.set(‘aRequestAsJson’, JSON.stringify(requestJson));

and printed console.log(" aRequestAsJson : " + requestJson);
it prints as " aRequestAsJson : [object Object]"

then in loading back scripts I printed aRequestAsJson to log :
var x = JSON.parse(pm.globals.get(“aRequestAsJson”)); //Nov 04
console.log(" aRequestAsJson in GET as JSON: " + x);

it printed as : " aRequestAsJson in GET as JSON: [object Object]"

then I printed the filed that I want to read as :
console.log("abbrDays from Request : " + x.body.abbrDays);

and it printed as “abbrDays from Request : undefined

How do I read the field values?

Hi @Mina_jk ,

You need to parse the part that returns from the body and pull its content, you can use it as follows.

const requestJson = pm.request.toJSON();
pm.globals.set('aRequestAsJson', JSON.stringify(requestJson));
const x = JSON.parse(pm.globals.get('aRequestAsJson'));
console.log(x.body.raw);
console.log(JSON.parse(x.body.raw).name);

1 Like

Thank You Yusuf, That worked!
Thanks a much!

1 Like