8

I have a POST call in Postman that returns this JSON object:

{
    "token": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiO3Jsb3Blei5hbnRvbmlvODVAZ21haWwuY29tIiwiZXhwIjoxNTkzNjc0MzUxLCJpYXQiOjE1MzMxOTQzNTF9.oTPVkcgF1QcoOsg6KDGOaaTyCQYrWS51QDdRn__MDigivcsuaqUgBhDaTYwQnxOtOCjxDRXO_cqK8i5xBq02bQ"
}

In my environment I set a variable named token

I want to set the value. I've tried with

var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("token", data.message.token);

and

var data = pm.response.json();
pm.environment.set("token", data.message.token);

but both with errors: SyntaxError | Invalid or unexpected token

en Peris
  • 1,537
  • 12
  • 31
  • 63

4 Answers4

4

If that's the only thing you get back in the response body, why are you adding 'message'?

Use data.token or just use pm.response.json().token and remove the variable declaration.

Danny Dainton
  • 23,069
  • 6
  • 67
  • 80
3
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("TOKEN",jsonData.token);
4b0
  • 21,981
  • 30
  • 95
  • 142
  • While this code may resolve the OP's issue, it is best to include an explanation as to how your code addresses the OP's issue. In this way, future visitors can learn from your post, and apply it to their own code. SO is not a coding service, but a resource for knowledge. Also, high quality, complete answers are more likely to be upvoted. These features, along with the requirement that all posts are self-contained, are some of the strengths of SO as a platform, that differentiates it from forums. You can edit to add additional info &/or to supplement your explanations with source documentation. – ysf Jun 21 '20 at 22:49
2

In order to set the environment variable key use below

var response=pm.response.json();
pm.environment.set("tokenkey", response.token);
Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
Tahera Firdose
  • 161
  • 1
  • 3
1

The environment variables were not working for me after a Postman update. In my case the problem was that my environment was not set on the top right (it was using the default, "No Environment"). ‍♂️

Paulo Merson
  • 13,270
  • 8
  • 79
  • 72