如何解析和测试响应作为数组中的键/值

时间:2019-03-28 14:20:59

标签: javascript arrays json postman

我有以下json响应:

{
"vin": "BAUV114MZ18091106",
"users": [
    {
        "role": "PRIMARY_USER",
        "status": "ACTIVE",
        "securityLevel": "HG_2_B",
        "firstName": "Etienne",
        "lastName": "Rumm",
        "nickName": "BastieW",
        "isInVehicle": false
    },
    {
        "role": "SECONDARY_USER",
        "status": "ACTIVE",
        "securityLevel": "HG_2_B",
        "firstName": "Test",
        "lastName": "DEde",
        "isInVehicle": false
    }
]
}

我想测试“ isInVehicle”键,如果通过,则通过测试,如果通过,则通过测试。

我试图使用下面的测试代码来执行此操作,但是不管我得到什么响应,它都无法正常工作,总是通过测试。

pm.test("User is in Vehicle", () => {
_.each(pm.response.json(), (arrItem) => {
    if (arrItem.isInVehicle === 'true') {
        throw new Error(`Array contains ${arrItem.isInVehicle}`)
    }
})
});

关于如何解决我的问题有什么想法吗?

2 个答案:

答案 0 :(得分:0)

我认为您正在遍历object(响应的根对象)而不是user array。修改后的版本将是:

var users = pm.response.users;
_.each(users, (arrItem) => {
    if (arrItem.isInVehicle) {
        //Do something  if isInVehicle is true 
    }
})
});

答案 1 :(得分:0)

您可以使用数组属性来完成这些操作

some-如果至少一个符合条件,则返回true

every-如果所有项目均符合条件,则返回true

const response = {
  "vin": "BAUV114MZ18091106",
  "users": [{
      "role": "PRIMARY_USER",
      "status": "ACTIVE",
      "securityLevel": "HG_2_B",
      "firstName": "Etienne",
      "lastName": "Rumm",
      "nickName": "BastieW",
      "isInVehicle": false
    },
    {
      "role": "SECONDARY_USER",
      "status": "ACTIVE",
      "securityLevel": "HG_2_B",
      "firstName": "Test",
      "lastName": "DEde",
      "isInVehicle": false
    }
  ]
};


pm.test("User is in Vehicle", () => {
  // I'm assuming you are looking for atleast one match
  const atleastOneMatch = response.users.some(user => user.isInVehicle);
  // if you are looking for all should match, uncomment the following code
  // const allShouldMatch = response.users.every(user => user.isInVehicle);
  
  if(atleastOneMatch) {
    // do your stuffs here
  }
})