How to Parse JSON Response in Postman: Simple Guide
In Postman, you can parse a JSON response by using
pm.response.json() in the Tests tab. This method converts the response body into a JavaScript object, allowing you to access values with dot notation or bracket notation.Syntax
Use pm.response.json() to convert the JSON response body into a JavaScript object. Then access properties using dot notation or bracket notation.
pm.response.json(): Parses the response body as JSON.jsonData.property: Access a property from the parsed JSON.
javascript
const jsonData = pm.response.json(); const value = jsonData.key; // Access value by key
Example
This example shows how to parse a JSON response and check if a specific value matches the expected result using an assertion.
javascript
pm.test("Status code is 200", () => { pm.response.to.have.status(200); }); const jsonData = pm.response.json(); pm.test("User name is correct", () => { pm.expect(jsonData.user.name).to.eql("John Doe"); });
Output
Test Results:
โ Status code is 200
โ User name is correct
Common Pitfalls
Common mistakes when parsing JSON in Postman include:
- Trying to parse a response that is not JSON, causing errors.
- Accessing properties that do not exist, leading to
undefinedvalues. - Not waiting for the response before parsing.
Always check the response content type and use safe property access.
javascript
/* Wrong way: Parsing non-JSON response */ // const jsonData = pm.response.json(); // This will throw error if response is not JSON /* Right way: Check content type before parsing */ if (pm.response.headers.get('Content-Type').includes('application/json')) { const jsonData = pm.response.json(); // safe to access jsonData properties }
Quick Reference
| Action | Code Snippet | Description |
|---|---|---|
| Parse JSON response | const jsonData = pm.response.json(); | Convert response body to JavaScript object |
| Access property | jsonData.key | Get value of 'key' from JSON object |
| Assert value | pm.expect(jsonData.key).to.eql('value'); | Check if value matches expected |
| Check content type | pm.response.headers.get('Content-Type') | Verify response is JSON before parsing |
Key Takeaways
Use pm.response.json() to parse JSON response into a JavaScript object.
Always verify the response content type is JSON before parsing.
Access JSON properties safely to avoid undefined errors.
Use pm.expect() assertions to validate parsed data in tests.
Parsing JSON in Postman helps automate API response validation easily.