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

Postman中支持数组与嵌套结构的JSON校验函数需求

适配数组与嵌套结构的Postman响应校验全局函数

修改后的全局函数代码

postman.setGlobalVariable("verifyResponseChildValueMatchesExact", (path, key, value) => {
    pm.test(`响应中路径 '${path.join(".")}' 下应存在键值对 '${key}: ${JSON.stringify(value)}'`, function() {
        let target = pm.response.json();
        
        // 遍历路径定位目标节点,兼容对象与数组
        for (const segment of path) {
            if (target === undefined || target === null) {
                throw new Error(`路径节点 '${segment}' 不存在,完整路径:${path.join(".")}`);
            }
            target = target[segment];
        }
        
        // 校验目标节点有效性及键值对匹配
        pm.expect(target).to.not.be.undefined.and.not.be.null;
        pm.expect(Object.keys(target)).to.include(key);
        pm.expect(target[key]).to.eql(value);
    });
});

关键改进点

  • 路径参数path支持混合字符串(对象键)与数字(数组索引),可定位任意层级的嵌套对象或数组元素
  • 内置路径遍历逻辑,不再依赖外部getResponseChild函数,独立性更强
  • 优化错误提示,明确指出路径中缺失的节点
  • 支持复杂类型(对象、数组)的深度相等校验

调用示例

  1. 验证数组指定索引的键值对(对应你的示例需求):
eval.globals.verifyResponseChildValueMatchesExact(["data", 0], "my_key", 42);
  1. 验证嵌套深层结构的键值对:
eval.globals.verifyResponseChildValueMatchesExact(["data", 0, "my_key2"], "my_key3", "value");
  1. 兼容原有非数组结构的调用:
eval.globals.verifyResponseChildValueMatchesExact(["data"], "my_key", 42);

注意事项

  • 数组索引必须传入数字类型(如0),而非字符串"0",否则会被识别为对象的字符串键
  • 确保接口响应为JSON格式,否则pm.response.json()会抛出解析错误
  • 使用eql进行值匹配,支持对象、数组等复杂类型的深度对比

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 07:39:58