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

Postman从JSON对象提取指定键值的实现方案

从API响应JSON中提取特定值的Pre-request Script实现

1. 提取所有id字段的值

在Postman的Pre-request Script中,可通过以下代码提取响应里content数组中所有条目的id值:

// 解析API返回的JSON响应
const responseData = pm.response.json();
// 遍历content数组,提取每个条目的id
const allIds = responseData.content.map(item => item.id);
// 将结果转为JSON字符串存入环境变量,供后续接口调用使用
pm.environment.set("allEmailIds", JSON.stringify(allIds));
// 控制台打印结果,方便调试
console.log("所有邮件id:", allIds);

这段代码会把所有id收集为数组,存入名为allEmailIds的环境变量,后续接口可直接引用该变量。

2. 提取from字段等于"rahul.sharma@gmail.com"对应的id值

要精准筛选指定发件人的id,使用以下代码:

const responseData = pm.response.json();
// 找到第一个from字段匹配的条目,提取其id
const targetId = responseData.content.find(item => item.from === "rahul.sharma@gmail.com")?.id;
if (targetId) {
    pm.environment.set("targetEmailId", targetId);
    console.log("匹配到的目标id:", targetId);
} else {
    console.log("没有找到发件人为rahul.sharma@gmail.com的邮件");
}

这里用find方法匹配第一个符合条件的条目,通过可选链?.避免找不到条目时报错;找到目标id后存入targetEmailId环境变量,未找到则在控制台给出提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 10:01:23