drew
drew

Reputation: 2371

Postman -- Unable to use environment variable when extracting from JSON response

I have a suite of postman collections. The server supports two type of user roles, partner and customer. The restful server URLs include the role name (e.g. http://server.com/customer/account and http://server.com/partner/account

The JSON data also differs by role.

"account" : {
  "customer" : {
    "name" : "Fred"
  }
}

"account" : {
  "partner" : {
    "name" : "Fred"
  }
}

I am trying to extract the name, but postman doesn't like the embedded environment variable specifying the role to use to extract the response. The environment variable works fine for creating the request.

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("user_name", jsonData.account.{{role}}.name);

Postman reports a syntax error (Unexpected '{' ) so I'm not hopeful, but is there a way to do this?

--- UPDATE --- I've found a workaround that is OK, but not as elegant.

if (environment["role"] == 'partner') {
  postman.setEnvironmentVariable("user_name", jsonData.account.partner.name);
} else {
  postman.setEnvironmentVariable("user_name", jsonData.account.customer.name);
}

Upvotes: 1

Views: 1330

Answers (1)

elssar
elssar

Reputation: 5861

Pre-request scripts and tests need to be valid javascript and so you cannot access global and environment variables using the {{var}} construct.

To make your tests look a bit better, you could do something like this

var jsonData = JSON.parse(responseBody),
    role = environment["role"];

postman.setEnvironmentVariable("user_name", jsonData.account[role].name);

Upvotes: 1

Related Questions