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

从ReadyAPI迁移至Postman:如何实现多层JSON结构的特定值存在性检查

在Postman中实现ReadyAPI风格的JSONPath存在性检查

刚从ReadyAPI转Postman做API测试是吧?我之前帮不少新手解决过这类迁移问题,你说的这个JSONPath存在性匹配断言,在Postman里用Tests脚本就能轻松实现,完全能替代ReadyAPI里的功能。

先给你理清楚步骤:

  • 打开你要加断言的Postman请求,切换到Tests标签页(就在请求编辑区最上方的选项栏里)
  • 在这个面板里写JavaScript脚本,Postman内置了Chai断言库,语法很直观

针对你提供的JSON示例,我给你几个具体的实现代码:

1. 检查最外层ilm节点是否存在

这完全对应你ReadyAPI里的<assertionOfType="JsonPath Existence Match", name="Check for existence of [ilm]">断言:

// 先把响应结果解析成JSON对象
const responseJson = pm.response.json();

// 创建测试用例,名称和你ReadyAPI里的保持一致
pm.test("Check for existence of [ilm]", function () {
    // 断言responseJson对象必须有'ilm'这个属性
    pm.expect(responseJson).to.have.property('ilm');
});

2. 检查更深层级的节点存在性

如果要检查比如ilm.hadr.qrep这种嵌套节点,有两种写法:

pm.test("Check for existence of [ilm.hadr.qrep]", function () {
    // 方式一:逐层检查,适合需要确认每一层都存在的场景
    pm.expect(responseJson.ilm).to.have.property('hadr');
    pm.expect(responseJson.ilm.hadr).to.have.property('qrep');

    // 方式二:链式嵌套检查,更简洁
    pm.expect(responseJson).to.have.nested.property('ilm.hadr.qrep');
});

3. 用JSONPath语法直接查询(更贴近ReadyAPI的习惯)

如果你更习惯用JSONPath的表达式来查询,Postman也支持:

pm.test("Check for existence of [ilm] via JSONPath", function () {
    // 用JSONPath表达式查询所有名为ilm的节点
    const queryResult = pm.response.jsonPath().get('$..ilm');
    // 断言查询结果不为空,说明节点存在
    pm.expect(queryResult).to.not.be.empty;
});

额外补充:检查数组中的特定值存在

如果之后需要检查比如activeServers数组里是否有某个特定值,也可以这么写:

pm.test("Check if 'testudb602l' exists in activeServers", function () {
    pm.expect(responseJson.ilm.hadr.activeServers).to.include('testudb602l');
});

写完脚本后,发送请求,Postman就会在Test Results里显示每个断言的通过/失败状态,和ReadyAPI的断言结果展示逻辑类似。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 19:43:15