【问题标题】:Postman get value from JSON where equals a value in array using javascript邮递员从 JSON 中获取值,其中等于使用 javascript 的数组中的值
【发布时间】:2019-07-20 23:08:28
【问题描述】:

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

我正在尝试从 JSON 响应正文中获取一个值并将其存储在环境变量中,但值“用户名”应该等于我的首选用户名。

通常我会提取这样的值:

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

这将给我列表中的第一项,但我确实希望获得列表中的第一项或第二项。例如,我希望获得 userid where username EQUAL "Billy"。

身体响应的输出:

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

有什么建议吗?

我记得在 SoapUI 中是这样的:

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

我想在 Postman 的 JS 中不可能做到这一点?

【问题讨论】:

标签: javascript arrays json postman


【解决方案1】:

您可以使用:Array.prototype.find():

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)

【讨论】:

  • 这行得通,但是每当我在 Postman 中用变量 {{username}} 更改“Billy”时,它就不起作用了?
  • 您应该检查如何在 Postman 中正确使用动态变量
  • 我也明白了 nvm :p 我会把它标记为答案,因为你是第一个!
【解决方案2】:

find() 作为另一个答案指出是这里最好的解决方案,但如果用户名不是唯一的,并且您想要用户名是“比利”的用户数组,那么请使用 filter()

const jsonData = {
  "Customers": [{
      "id": 24,
      "userid": 73063,
      "username": "BOB",
      "firstname": "BOB",
      "lastname": "LASTNAME"
    },
    {
      "id": 25,
      "userid": 73139,
      "username": "Billy",
      "firstname": "Billy",
      "lastname": "lasty"
    }
  ]
}
console.log(jsonData.Customers.filter(c => c.username === 'Billy'))

【讨论】:

  • 请注意Array.prototype.filter() 的性能不佳,因为它会过滤整个array.. 而且您只需找到第一个,因为username 是唯一的
  • @YosvelQuintero 我已经说过.find() 更好,当用户名不唯一时使用.filter()。此外,您假设用户名是唯一的,因为问题没有提供该信息。
【解决方案3】:

你的userid也可以使用filter获取,如下-

const data = {
  "Customers": [{
      "id": 24,
      "userid": 73063,
      "username": "BOB",
      "firstname": "BOB",
      "lastname": "LASTNAME"
    },
    {
      "id": 25,
      "userid": 73139,
      "username": "Billy",
      "firstname": "Billy",
      "lastname": "lasty"
    }
  ]
};
const username = 'Billy';
const user = data.Customers.filter(obj => obj.username.toLowerCase() === username.toLowerCase())[0];
const userid = user ? user['userid'] : null;

console.log(userid);

注意:.toLowerCase()在这里是可选的,你可以根据自己的情况使用。

那么你可以简单地将它设置为 -

pm.environment.set("useridToken", userid);

【讨论】:

    【解决方案4】:

    在 Postnam 测试脚本中,您可以使用some Javascript 功能。在你的情况下,有太多的方法要做。 我将向您展示如何使用Array.find 函数解决您的问题:

    var jsonData = pm.response.json();
    var user = jsonData.Customers.find(function(user) {
        return user.username === 'Billy';
        // OR you could config username in postman env
        // return user.username === pm.variables.get("username_to_find"); 
    });
    pm.environment.set("useridToken", user.userid);
    

    【讨论】:

      【解决方案5】:

      试试这个

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

      【讨论】:

        【解决方案6】:

        重复 the currently highest voted answer, 稍作修改。
        还添加了一个受启发的解决方案 the other Lodash answer.1

        const jsonData = {
          Customers: [{
            id: 24,
            userid: 73063,
            username: 'BOB',
            firstname: 'BOB',
            lastname: 'LASTNAME'
          }, {
            id: 25,
            userid: 73139,
            username: 'Billy',
            firstname: 'Billy',
            lastname: 'lasty'
          }]};
        for (const i in jsonData.Customers) {
          console.log('userid of customer['+i+']: '+jsonData.Customers[i].userid);
        }
        const userId_UsingFind = (name) => {
          const user = jsonData.Customers.find(item => item.username === name);
          return user ? user.userid : user;
        };
        console.log('Using .find(), userid of "Billy": '+userId_UsingFind('Billy'));
        console.log('Using .find(), userid of "Joe": '+userId_UsingFind('Joe'));
        
        const userId_Native = (name) => {
          for (const i in jsonData.Customers) {
            if (jsonData.Customers[i].username === name) {
              return jsonData.Customers[i].userid;
            }
          }
        };
        console.log('Native loop, userid of "Billy": '+userId_Native('Billy'));
        console.log('Native loop, userid of "Joe": '+userId_Native('Joe'));

        如代码所示,使用.find() 的解决方案既简短又优雅。


        1 假设期望的结果是 firstuserid Billy。检索 所有 次出现的userid:s 数组Billy,见answer that returns an array of userid:s

        【讨论】:

          【解决方案7】:

          此答案显示了使用 JavaScript 库的解决方案 Lodash.
          不是作为建议,而只是为了证明它是 可能使用 Lodash。
          它的灵感来自 the other lodash answer.1

          const jsonData = {
            Customers: [{
              id: 24,
              userid: 73063,
              username: 'BOB',
              firstname: 'BOB',
              lastname: 'LASTNAME'
            }, {
              id: 25,
              userid: 73139,
              username: 'Billy',
              firstname: 'Billy',
              lastname: 'lasty'
            }]
          };
          
          const userId_Lodash = (name) => {
            let userId;
            _.forEach(jsonData.Customers, (item) => {
              if (item.username === name) { userId = item.userid; }
            });
            return userId;
          };
          console.log('Lodash loop, userid of "Billy": ' + userId_Lodash('Billy'));
          console.log('Lodash loop, userid of "Dave": ' + userId_Lodash('Dave'));
          <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.19/lodash.js"></script>

          对于手头的问题,我看不出有什么特别的理由要使用 Lodash 图书馆。
          但在其他示例中,它可能更有意义。


          1 发布的问题没有说明期望的结果是否是 第一个 userid匹配Billy,或所有这样的用户ID:s。 这个答案给出了第一个命中。

          【讨论】:

            【解决方案8】:

            这个答案的灵感来自 other answer that outputs an array1

            原始海报没有明确说明是否需要输出 应该是 single userid(大概是第一次出现?) - 或 一个数组,包含 all userid:s 匹配“Billy”。

            这个答案显示了后一种情况的解决方案,方法是使用 Lodash.

            const jsonData = {
              Customers: [{
                userid: 73063,
                username: 'BOB'
              }, {
                userid: 73138,
                username: 'Billy'
              }, {
                userid: 74139,
                username: 'Billy'
              }]
            };
            
            const userIds = [];
            _.forEach(_.filter(jsonData.Customers, c => c.username === 'Billy'),
              item => { userIds.push(item.userid); });
            console.log(userIds);
            <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.19/lodash.js"></script>

            1 这个答案很有帮助,因为它暗示了如何过滤掉 Customers 数组的相关对象。然而,原来的海报 想要(一个数组)userid(s),它是一个 number,而不是一个数组 包含 userid:s 的对象。这就是我的答案 不同。

            【讨论】:

            • 这对我来说实际上是最好的解决方案,因为 .find 语法没有作为选项出现,只有 .filter 工作。谢谢@henke
            猜你喜欢
            • 2018-11-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-01-12
            • 1970-01-01
            • 2019-11-12
            • 2018-04-15
            • 1970-01-01
            相关资源
            最近更新 更多