json 如何检查POSTMAN中是否存在对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43973926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if an object exist in POSTMAN?
提问by Mehdy Driouech
I want to know how can i test if an object exist. For example my API return these things :
我想知道如何测试对象是否存在。例如我的 API 返回这些东西:
"data": [
{
"id": 1,
"name": "Abu Dhabi",
"locale": "AE",
"rentWayCountryId": 242,
"stations": [
{
"id": 2,
"rentWayName": "ABU DHABI AIRPORT",
"rentWayStationId": "IAEAUH1",
"bindExtrasToStationToExtraCategory": []
}
]
},
I want to check that data.id exist.
我想检查一下 data.id 是否存在。
I used the test options in postman and i did this :
我在邮递员中使用了测试选项,我这样做了:
var jsonData = JSON.parse(responseBody);
tests["Name value OK"] = jsonData.data.id === "1";
Could you tell me witch condition should i use to verify only if the data exist.
你能告诉我我应该使用女巫条件来验证数据是否存在。
Thanks you very much !!
非常感谢你 !!
回答by EricWasTaken
Here is a proper Postman test:
这是一个正确的邮递员测试:
const jsonData = pm.response.json();
pm.test('Has data', function() {
pm.expect(jsonData).to.have.property('data');
});
The above will either PASS or FAIL yor postman request based on the presence of the dataproperty in the response.
以上将根据data响应中属性的存在来通过或失败您的邮递员请求。
回答by Abdullah Danyal
To check whether the object is exist or not is equivalent to check whether it is null or not.
检查对象是否存在等同于检查它是否为空。
if(object){//runs if object is not null}
回答by Mehdy Driouech
Thanks for the idea ! i tried this :
谢谢你的主意!我试过这个:
var jsonData = JSON.parse(responseBody);
tests["idExist"] = jsonData.data.id !== null ;
and it worked. Thanks very much
它奏效了。非常感谢
回答by uBaH
If you need to check if variable is being set, use this solution:
如果您需要检查是否正在设置变量,请使用以下解决方案:
tests["idExist"] = pm.globals.get('dealerId') !== undefined;

