Vinoth
Vinoth

Reputation: 93

How to extract the values from the response body in postman

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.

Upvotes: 9

Views: 35118

Answers (2)

Moeez Mazhar
Moeez Mazhar

Reputation: 672

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

Upvotes: 18

Leonardo de Oliveira
Leonardo de Oliveira

Reputation: 71

You are using a notation pattern that is deprecated.

Instead of set your variable using:

var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("currentUniqueId", data.UniqueId);

Try to set your variable this way:

pm.environment.set('currentUniqueId', pm.response.json().UniqueID);

To get more information, try: https://learning.getpostman.com/docs/postman/scripts/test_examples/

Upvotes: 3

Related Questions