How to Assert JSON Value in Postman Tests Easily
In Postman, you can assert JSON values by writing test scripts using
pm.test and pm.response.json(). Extract the JSON response, then use pm.expect to check if a specific key has the expected value.Syntax
Use pm.test to define a test case with a description. Inside it, call pm.response.json() to parse the JSON response body. Then use pm.expect with a matcher like .to.eql() to assert the value.
pm.test("Test description", function () { ... }): Defines a test.pm.response.json(): Parses the response body as JSON.pm.expect(actual).to.eql(expected): Checks if actual equals expected.
javascript
pm.test("Check JSON value", function () { const jsonData = pm.response.json(); pm.expect(jsonData.key).to.eql("expectedValue"); });
Example
This example shows how to assert that the JSON response has a key status with value success. It runs after the API response is received.
javascript
pm.test("Status is success", function () { const jsonData = pm.response.json(); pm.expect(jsonData.status).to.eql("success"); });
Output
PASS Status is success
Common Pitfalls
Common mistakes include:
- Not parsing the response JSON before accessing keys.
- Using incorrect key names or case sensitivity.
- Comparing values with wrong types (e.g., string vs number).
- Not handling nested JSON objects properly.
Always check the exact JSON structure and use correct keys.
javascript
/* Wrong way: missing JSON parse */ pm.test("Wrong test", function () { pm.expect(pm.response.json().status).to.eql("success"); // This will fail if pm.response.body is not parsed }); /* Right way: parse JSON first */ pm.test("Right test", function () { const jsonData = pm.response.json(); pm.expect(jsonData.status).to.eql("success"); });
Quick Reference
| Action | Code Snippet | Description |
|---|---|---|
| Define test | pm.test("desc", function () { ... }) | Create a test case with description |
| Parse JSON | const jsonData = pm.response.json(); | Get JSON object from response body |
| Assert value | pm.expect(jsonData.key).to.eql(value); | Check if key equals expected value |
| Check nested | pm.expect(jsonData.parent.child).to.eql(value); | Assert nested JSON key value |
| Check type | pm.expect(typeof jsonData.key).to.eql('string'); | Assert data type of value |
Key Takeaways
Always parse the response JSON with pm.response.json() before assertions.
Use pm.test to group assertions with clear descriptions.
Use pm.expect(actual).to.eql(expected) for exact value checks.
Check JSON keys carefully for correct spelling and case.
Handle nested JSON by accessing keys step-by-step.