Creating variable from response (old syntax vs. new syntax question)

Hello,

I am working on test scripts and I discovered this blog post. I’m particularly interested in this code:

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable(“token”, jsonData.token);

This is simple piece of code but it helps a lot and works very well but as I understand this syntax is old. My question is: how it should looks like in new syntax?

I’ve already tried:

var response = JSON.parse(responseBody);
pm.globals.set(“job_id”, response.job_id);

And it works but is it correct? I have some doubts about 1st line because I often see something like this:

let jsonData = pm.response.json();
pm.environment.set(“eventId”, jsonData.events[0][“event_id”]);

Could someone helps me understand the difference?

Hi @meatinaplasticsack

pm. is the “new” Postman API… So my understanding is that both will work but the latest API should/would be more efficient. So I would use;

let jsonData = pm.response.json();
pm.environment.set(“eventId”, jsonData.events[0][“event_id”]);

This is also shown in the official Postman Documentation;

image

I do some research and I think new syntax for:

should be something like this:

let response = pm.response.json();
pm.environment.set(“job_id”, response.job_id);

And this:

is for something more advanced like getting value form response that is array with many objects.

I wouldn’t consider it more advanced per-say, I just copied your example from above.

It is referring to an array index and it also uses bracket notation.
(You can use both bracket and (dot) notation when referring to properties in your response).

If you don’t have an array in your response you don’t need to reference the index but if you do, this is the standard way of accessing the property within an array.

Hope that helps explain a bit??