【问题标题】:Grabbing a specific value from a response从响应中获取特定值
【发布时间】:2019-08-26 20:40:52
【问题描述】:

我正在尝试根据响应中的特定值设置邮递员环境变量。

我不确定用于获取价值的代码。

我知道我需要将响应设置为变量,如下所示:

var response = JSON.parse(responseBody);

而且我知道我可以使用以下内容来设置我的环境变量:

postman.setEnvironmentVariable("category_ref",myVariableName);

以下是我的回复中的一个 sn-p:

{
    "id": 45,
    "name": "Accommodation",
    "description": ""
},
{
    "id": 46,
    "name": "Accommodation (Engineering)",
    "description": ""
},

我想根据我已经知道的“名称”值获取“id”值。

举个例子,我希望我的代码给我一个 ID,其中 "name" = "Accommodation"

编辑:

根据以下答案更改为原始问题。

我的测试代码现在如下所示:

//Ensure the API Test Category is present
var response = JSON.parse(responseBody);
tests["my test"] = responseBody.has("Accommodation");

//pass in id into variable for delete step
var requiredId = pm.response.json().find(function(element){
    if (element.name == "Accommodation"){
        return element.id;
    }
});

stringId = JSON.stringify(requiredId);

pm.environment.set("category_ref",stringId);

console.log("my string "+stringId);

我到控制台的输出如下所示,这也是发送到 category_ref 环境变量的值:

my string {"id":45,"name":"Accommodation","description":""}

剩下的问题是我不想像上面那样返回所有元素,我只想返回“45”,这是 name = 住宿的 id 值。

【问题讨论】:

标签: javascript json postman


【解决方案1】:

Postman 中的测试除了 JavaScript 之外,还可以使用Array.find(),如下所示,

响应正文:

[
    {
        "id": 45,
        "name": "Accommodation",
        "description": null
    },
    {
        "id": 46,
        "name": "Accommodation (Engineering)",
        "description": null
    }
]

测试窗口:

var matchedItem = pm.response.json().find(function(element) {
    if (element.name == "Accommodation") {
        return element;
    }
});

console.log(matchedItem.id);

【讨论】:

  • 谢谢。这很棒。我尝试用console.log("my string "+requiredId); 显示我的价值,但输出是my string [object Object],所以我想知道我是否需要转换为字符串或其他东西?
  • 越来越近了。字符串化工作。但现在我的输出是my string {"id":45,"name":"Accommodation","description":""},因为我希望只看到45 的值。
  • 是的,肯定会使用它。从这里的代码粘贴 - if (element.name == "Accommodation"){ return element.id;
  • 对不起。我只看到测试窗口中的 var 名称发生了变化,而没有看到对数组 find 的引用。
  • 非常感谢所有这些帮助。工作完美,下次教我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-10
  • 1970-01-01
  • 2021-04-14
  • 2021-12-19
  • 2021-11-05
相关资源
最近更新 更多