邮递员从JSON获取值,其中使用javascript等于数组中的值 [英] Postman get value from JSON where equals a value in array using javascript

查看:53
本文介绍了邮递员从JSON获取值,其中使用javascript等于数组中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前使用的是最新版本的Postman:6.7.4(最新)

Currently using the latest version of Postman: 6.7.4 (Latest)

我正在尝试从JSON响应主体中获取一个值并将其存储在环境变量中,但值'username'应该等于我的首选用户名.

I'm trying to get a value out of a JSON response body and store it in an environment variable BUT the value 'username' should be equal to my preferred username.

通常我会提取一个像这样的值:

Normally I would extract a value like this:

var jsonData = pm.response.json();
pm.environment.set("useridToken", jsonData.Customers[0].userid);

这会给我列表中的第一项,但我希望从列表中获得第一项或第二项.例如,我希望获得 userid 其中 username 等于"Billy".

This would give me the first item in the list but I do not wish to obtain the first nor the second item from the list. I wish to obtain the userid where username EQUAL "Billy" for example.

身体反应的输出:

{
"Customers": [
    {
        "id": 24,
        "userid": 73063,
        "username": "BOB",
        "firstname": "BOB",
        "lastname": "LASTNAME
    },
    {
        "id": 25,
        "userid": 73139,
        "username": "Billy",
        "firstname": "Billy",
        "lastname": "lasty"
    }
   ]
}

有什么提示吗?

我记得在SoapUI中是这样的:

I remember in SoapUI it was like this:

$.channels[?(@.is_archived=='false')].id[0]

我想在邮递员的JS中不可能做到这一点?

I guess it's not possible to do this in JS in Postman?

推荐答案

您可以使用:

const data = {
  "Customers": [{
      "id": 24,
      "userid": 73063,
      "username": "BOB",
      "firstname": "BOB",
      "lastname": "LASTNAME"
    },
    {
      "id": 25,
      "userid": 73139,
      "username": "Billy",
      "firstname": "Billy",
      "lastname": "lasty"
    }
  ]
};

const user = data.Customers.find(u => u.username === 'Billy');
const userid = user ? user.userid : 'not found';

console.log(user);
console.log(userid);

这篇关于邮递员从JSON获取值,其中使用javascript等于数组中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆