![](/img/trans.png)
[英]POSTMAN : parsing a JSON response, how deep can I go into the response?
[英]Postman: How can validate a key in JSON response
我需要驗證接下來的 2 個鍵: key1
和key2
:
{
"data": [
{
"id": "123",
"type": "something",
"created": "1540952074",
"test": [
{
"key1": "asd123",
"key2": "166802"
}
]
},
我只對驗證這些密鑰是否已經存在感興趣。
我做了這個測試:
pm.test('returns the correct parameters by type', () => {
for (i = 0; i < jsonData.data.length; i++) {
if (jsonData.data[i].type === 'something') {
// for (j = 0; j < jsonData.data.test.length; j++) {
pm.expect(jsonData.data[i]).to.have.property('id');
pm.expect(jsonData.data[i]).to.have.property('type');
pm.expect(jsonData.data[i]).to.have.property('created');
pm.expect(jsonData.data[i].test[0]).to.have.property('key1');
pm.expect(jsonData.data[i].test[0]).to.have.property('key2');
}
}
});
返回以下錯誤:
returns the correct parameters by type | TypeError: Cannot read property '0' of undefined
但是如果我把一個帶有jsonData.data[i].test[0]
的 console.log ,控制台會正確地向我顯示兩個參數到一個對象中:
Object:{}
key1:"asd123"
key2:"166802"
知道我該怎么做嗎?
謝謝
我真的看不到完整的響應數據,但這可能對你有用:
let jsonData = {
"data": [
{
"id": "123",
"type": "something",
"created": "1540952074",
"test": [
{
"key1": "asd123",
"key2": "166802"
}
]
}
]
}
pm.test("My Test", () => {
_.each(jsonData.data, (item) => {
if(item.type === "something") {
pm.expect(_.first(item.test)).to.have.keys('key1', 'key2')
}
})
})
由於這只是使用來自其jsonData
對象的數據的測試示例,因此這不適用於您的響應數據。
你可以試試這個嗎?
pm.test("My Test", () => {
_.each(pm.response.json().data, (data) => {
if(data.type === "something") {
_.each(data.test, (test) => {
pm.expect(test).to.have.keys('key1', 'key2')
})
}
})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.