Difference between pm.response.json() and JSON.parse(responseBody)

Viewed 3842

What is the fundamental difference between

const json_response = pm.response.json()

and

json_response = JSON.parse(responseBody)
2 Answers

In the Postman sandbox context, JSON.parse(responseBody) and pm.response.json() is doing the same thing.

The pm.* API hasn't been in the product the whole time and was introduced to cover lots of different actions that users would normally take when accessing things like, the response body.

Previously, users would use JSON.parse(responseBody) in the sandbox environment to get this data.

Here's the full list of the pm.* API methods but this can also be seen in the app with the auto-suggestion feature when you type pm.

https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/

I would personally recommend that you use the pm.repsonse.json() method in the app.

As Danny Dainton has already pointed out, JSON.parse(responseBody) and pm.response.json() do the same thing - they both return the response body of your API request as a string in JSON format.

Concerning the missing const declaration in the second statement. - If you put the two statements in the same file, then clearly you are correct to leave out the const declaration in the second statement.
(Otherwise there will be a syntax error: Identifier 'json_response' has already been declared.)

But since the two statements do the same thing, it makes no sense to have them both in the same script. And if they are not in the same script, a declaration is necessary in the second statement as well as in the first.

Related