如何通过脚本在Postman中折叠JSON响应内的指定数组
Postman响应指定数组折叠实现方案
可行性结论
可以实现,你提到的在Test标签页遍历修改响应的思路完全可行,共有两种常用实现方式:
方案1:直接修改响应体简化展示
直接修改Response的Body页中展示的内容,把指定数组替换为折叠提示文本:
// 获取原始响应JSON const res = pm.response.json(); // 遍历响应,替换目标数组 res.forEach(item => { // 校验目标数组存在且为数组类型时执行替换 if (item?.attribute1?.attribute3 && Array.isArray(item.attribute1.attribute3)) { // 可自定义替换文本,比如保留数组长度信息 item.attribute1.attribute3 = `[折叠数组,共${item.attribute1.attribute3.length}项]`; } }) // 覆盖原始响应体,格式化输出 pm.response.setBody(JSON.stringify(res, null, 2));
- 优势:无需切换标签,直接在Body页就能看到简化后的结构
- 劣势:临时修改了响应内容,需要用到原始数组数据时要注释掉脚本再发请求
方案2:通过可视化面板展示简化结构
不修改原始响应,仅在Visualize标签页渲染折叠后的结构:
const res = pm.response.json(); // 处理折叠逻辑,不修改原始响应数据 const processedRes = res.map(item => { const temp = {...item}; if (temp?.attribute1?.attribute3 && Array.isArray(temp.attribute1.attribute3)) { temp.attribute1.attribute3 = `[折叠数组,共${temp.attribute1.attribute3.length}项]`; } return temp; }) // 渲染到可视化面板 pm.visualizer.set(`<pre>{{data}}</pre>`, { data: JSON.stringify(processedRes, null, 2) })
- 优势:原始响应完整保留,需要看完整数据切回Body页即可,灵活度更高
- 劣势:需要手动切换到Visualize标签查看简化结构
补充说明
如果需要折叠的数组嵌套层级不固定,可以写递归遍历函数匹配指定字段名,无需手动写死层级路径。折叠提示文本也可以自定义,比如保留前2项数据再加省略号,方便快速预览部分内容。
内容的提问来源于stack exchange,提问作者2d89
相关产品推荐
相关产品推荐

