【问题标题】:Get particular value from json list use javascript in postman testing从 json 列表中获取特定值 在邮递员测试中使用 javascript
【发布时间】:2018-11-23 16:14:32
【问题描述】:

我正在使用邮递员进行 API 测试。 我的回复信息是

[
    {
        "firstName": "Jia",
        "lastName": "Tes",
        "memberId": 745794,
        "branchId": 12442,
        "branchName": "NZ - Clubware Mobile Test Branch 1"
    },
    {
        "firstName": "Jia",
        "lastName": "Test2",
        "memberId": 745746,
        "branchId": 12442,
        "branchName": "NZ - Clubware Mobile Test Branch 1"
    },
    {
        "firstName": "Jia",
        "lastName": "Test3",
        "memberId": 745748,
        "branchId": 12443,
        "branchName": "Clubware Mobile Test Branch 2 (Pub)"
    },
    {
        "firstName": "Jia",
        "lastName": "Test3",
        "memberId": 745745,
        "branchId": 12442,
        "branchName": "NZ - Clubware Mobile Test Branch 1"
    }
]

我想获取“memberId”,其中“firstName”:“Jia”,“lastName”:“Test3”和“branchName”:“NZ - Clubware Mobile Test Branch 1”

我现在的代码是这样的

var response = JSON.parse(responseBody);
console.log("BODY:" + response[3].memberId);

但是我不喜欢使用索引来定位列表中的元素,我该怎么做呢,谢谢大家!!

【问题讨论】:

  • 尝试response.find(e => e.firstName === 'Jia' && e.lastName === 'Test3' && ... etc).memberId - 了解更多关于数组查找方法read the documentation
  • @JaromandaX,非常感谢,你的建议很棒!

标签: javascript json postman


【解决方案1】:

如果您只想检查特定值,可以使用_.find() Lodash 函数来获取memberId 值:

var user = _.find(pm.response.json(), { 
    firstName: "Jia", 
    lastName: "Test3", 
    branchName: "NZ - Clubware Mobile Test Branch 1" 
})
console.log(user.memberId)

【讨论】:

    【解决方案2】:
    var response = [    {
            "firstName": "Jia",
            "lastName": "Tes",
            "memberId": 745794,
            "branchId": 12442,
            "branchName": "NZ - Clubware Mobile Test Branch 1"
        },
        {
            "firstName": "Jia",
            "lastName": "Test2",
            "memberId": 745746,
            "branchId": 12442,
            "branchName": "NZ - Clubware Mobile Test Branch 1"
        },
        {
            "firstName": "Jia",
            "lastName": "Test3",
            "memberId": 745748,
            "branchId": 12443,
            "branchName": "Clubware Mobile Test Branch 2 (Pub)"
        },
        {
            "firstName": "Jia",
            "lastName": "Test3",
            "memberId": 745745,
            "branchId": 12442,
            "branchName": "NZ - Clubware Mobile Test Branch 1"
        }
    ]; var i;
    
    for(i =0; i <response.length ; i++)
    { 
      if(response[i].firstName == 'Jia' && response[i].lastName == 'Test3' 
         && response[i].branchName == 'NZ - Clubware Mobile Test Branch 1')
      {
        console.log(response[i].memberId);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-01
      • 1970-01-01
      • 2019-07-20
      • 2015-08-25
      • 2013-08-20
      • 1970-01-01
      • 1970-01-01
      • 2018-06-14
      • 1970-01-01
      相关资源
      最近更新 更多