You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostMan 6.0.10测试脚本编写:如何查询与检查响应JSON

Postman 6.0.10: Testing JSON Response Structure & Content

Got it, let's break down how to write those test scripts for Postman 6.0.10 to check your JSON responses properly. I'll walk you through verifying if the response is a single JSON object, plus some common related checks you might need.

First: Get Parsed JSON from the Response

Before you can check anything, you need to parse the response body into a usable JavaScript object. Postman makes this super straightforward with:

const responseJson = pm.response.json();

This line takes the raw response body, parses it as JSON, and stores it in the responseJson variable for easy access.

Test 1: Verify Response is a Single JSON Object

To confirm the response is a single object (not an array, null, or other data type), you'll need to check three things:

  1. The parsed value is an object type
  2. It's not null (since typeof null incorrectly returns object in JS)
  3. It's not an array (arrays are also considered object types in JS)

Here's the complete test script:

pm.test("Verify the response is a single JSON object", function () {
    const responseJson = pm.response.json();
    
    // Check the type is object
    pm.expect(typeof responseJson).to.eql('object');
    // Ensure it's not null
    pm.expect(responseJson).to.not.be.null;
    // Confirm it's not an array
    pm.expect(Array.isArray(responseJson)).to.be.false;
});

Bonus: Check Specific Fields in the JSON Object

Once you've confirmed it's a single object, you'll often want to verify specific fields exist and have the correct values/types. For example, if your response should have an id (number) and email (string) field:

pm.test("Verify required fields exist and have valid types", function () {
    const responseJson = pm.response.json();
    
    // Check that the "id" property exists and is a number
    pm.expect(responseJson).to.have.property('id');
    pm.expect(typeof responseJson.id).to.eql('number');
    
    // Check that the "email" property exists and is a string
    pm.expect(responseJson).to.have.property('email');
    pm.expect(typeof responseJson.email).to.eql('string');
    // Optional: Check that the email matches a valid format
    pm.expect(responseJson.email).to.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/);
});

A Quick Note on Assertions

Postman uses the Chai Assertion Library under the hood with pm.expect(), so you can use all the standard Chai syntax for more complex checks (like equality, ranges, includes, etc.). This gives you tons of flexibility for testing your responses.

内容的提问来源于stack exchange,提问作者smeeb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:24:38