首页 > 解决方案 > 如何将响应解析和测试为数组中的键/值

问题描述

我有以下 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}`)
    }
})
});

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

标签: javascriptarraysjsonpostman

解决方案


您可以使用数组属性来执行这些操作,

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
  }
})


推荐阅读