I would like to use Postman to set an Environment variable in a dynamic way and use the dataObject..attribute2's values based on the request name. This script is used within the Pre-req section.
Situation: I have a json data object:
var dataObject = {
"request01": {
"attribute1": 123456789,
"attribute2": "asdfghjkl"
},
"request02": {
"attribute1": 987654321,
"attribute2": "lkjhgfdsa"
}
}
And I have these 2 requests in the same folder with the names:
Now, I want to define the value of this allocation, so I assign the attribute2 value to the variable dynamicAttribute2. If I do this in a static way it is like this:
postman.setEnvironmentVariable("dynamicAttribute2", dataObject.request02.attribute2);
Now this question how to do it properly in a dynamic way, depending on the request name, each. I tried to do this:
postman.setEnvironmentVariable("dynamicAttribute2", dataObject.{request.info.name}.attribute2);
The issue is that Postman cannot resolve the object reference to the attribute.
Question
What's the correct way to use this?
The correct syntax to get the Request Name
is:
pm.info.requestName
So you would need to use something like this to get the value you want:
pm.environment.set("dynamicAttribute2", dataObject[`${pm.info.requestName}`].attribute2);
It might be worth you taking a look through this to learn more about the pm.*
API functions:
https://learning.getpostman.com/docs/postman/scripts/postman_sandbox_api_reference/#pm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With