代码之家  ›  专栏  ›  技术社区  ›  Yu Jia

从JSON列表获取特定值在postman测试中使用javascript

  •  1
  • Yu Jia  · 技术社区  · 6 年前

    我正在使用Postman进行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);
    

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

    2 回复  |  直到 6 年前
        1
  •  3
  •   Danny Dainton    6 年前

    如果只想检查特定值,可以使用

    var user=.find(pm.response.json(),){
    名:“佳”,
    姓氏:“test3”,
    分支机构名称:“NZ-俱乐部软件移动测试分支机构1”
    })
    console.log(用户.memberid)
    

    Lodash函数得到memberId价值观:

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

    Postman Response

        2
  •  2
  •   dkm007    6 年前
    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);
      }
    }