jsonpostman

How to access a property of a JSON object stored as environment variable from within the request body?


Here I am storing the response object in the environment variable.

   let res = pm.response.json(); 
   postman.setEnvironmentVariable('currentUser', JSON.stringify(res));

res object has a property called "userId"

In another request body I want to set the userId to the value stored in the currentUser object. Something like this.

"userId": "{{currentUser.userId}}",

But this didn't work.

Converting to JSON also didn't work.

"userId": "{({JSON.parse(currentUser)).userId}}",

Is it possible to do this in Postman?

EDIT

There are many properties in the object that are used in different other requests. I was thinking that rather than creating environment variable for each an every one of them, if I could just save the object and pass them when needed. That was the reasoning behind it.


Solution

  • Would something like this do the same thing for you?

    let userId = pm.response.json().userId
    pm.environment.set('currentUser', userId)
    

    Then use it like this:

    "userId": "{(userId}}"
    

    Not sure what the reasoning is behind storing the whole response for a single value, within the data.


    Edit

    You can add this to the Pre-request Script of the second request:

    pm.environment.set("userId", JSON.parse(pm.environment.get('currentUser')).userId)
    

    And then reference it, in the same way as I mentioned above, within the POST request body.