javascript - 如何将响应解析和测试为数组中的键/值
问题描述
我有以下 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}`)
}
})
});
关于如何解决我的问题有什么想法吗?
解决方案
您可以使用数组属性来执行这些操作,
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
}
})
推荐阅读
- angular - 如何根据用户点击角度显示数据
- apache-kafka - 对两个不同的环境使用相同的 kafka 主题
- puma - 为什么在部署后找不到我的数字海洋空间的 Rails 凭据?
- merge - 合并在日期上匹配的查询,如果未找到匹配项则保留 null
- php - ErrorException:试图获取非对象的属性“max_score”
- java - 花花公子进入 RecycleView 的 Android 应用程序
- html - 如果部分中没有值,则显示“无评论”
- linux - Ubuntu Bind9 DNS 在互联网上不可用
- python-3.x - 打开简历发现奇怪的轮廓
- python - Python 到 C 使用 Cython 和依赖项