After posting the request, API return response body as string
Response body look like
{ UniqueID = 93243434,birthGender = M,birthDate = 11/1/2018 5:51:18 PM, familyNames = James, givenNames = Test }
when I try to set the environment variable using the below code
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("currentUniqueId", data.UniqueId);
I got the below error on test results
Error message: There was an error in evaluating the test script: JSONError: Unexpected token 'U' at 1:3 { UniqueID = 93243434,birthGender = M,birthDate = 11/1/2018 5:51:18 PM, family ^
my goal is I need to extract the value 93243434 and assign to environment variable.
Notice we got our response in nested JSON object array schema. To extract data from JSON object array we can use any online tool like JSON Path Finder. · Copy the path for desired node as shown below to use it in Postman Just hit the Send button and console output shows that we Successfully extracted data from JSON response body
All you have to do is call postman.setEnvironmentVariable (key, value) or postman.setGlobalVariable (key, value) to set a variable with values you have extracted from the response. You can even add something dynamically generated through Javascript. Lets go through an example which will illustrate this in more detail:
JSON.parse (responseBody); is for extract data which is in json format not in text format Thanks in advance. Hi, Abhinav! Thank you for this post! Amazing, this helps me a lot. Hi, Thanks for this post. I’m having so many issues time to time on test scripting in postman.
You were on the right lines with logging the response to the Postman Console. This is what it would have logged: This is showing you that resources is an array with 1 object and if you were to expand this, you will see that the objects are zero-indexed.
Hi you are using the correct way but you can try this version
var jsonData = pm.response.json();
pm.environment.set("UNIQUE_ID", jsonData.UniqueID);
The set("UNIQUE_ID"
will help you save it in variable and you can name it as you want and jsonData.uniqueID
will extract what you want to get from the Json response
If you view my approach I am extracting Access code and company id and saving it in variable and calling it in all next api's
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