我发送了一个请求,它给我发回了类似这样的内容:
{
"items": [
{
"id": 86154,
...
},
{
"id": 86194,
...
}
}
我想在 Postman 测试部分计算这个数组的大小。所以我写道:
var body = JSON.parse(pm.response.json());
tests["Count: " + body.items] = true;
正如您在上面看到的,它没有用。我对 PostMan 和 Javascript 都不熟悉,这可能就是原因。
最佳答案
简单的答案是得到同样的东西,使用新的 pm.*
API 语法:
pm.test(`Count: ${pm.response.json().items.length}`)
您使用的语法不正确 JSON.parse(pm.response.json())
- 您可以只使用 pm.response.json()
并删除JSON.parse()
.
要获得对象的数量,你只需要使用.length属性(property)。
我不确定您要测试什么,但这个简单的测试将检查或断言您在数组中有 2 个对象(如您的示例):
let body = pm.response.json()
pm.test("Check the Items array length", () => {
pm.expect(body.items.length).to.equal(2)
})
这是使用较新的 pm.test()
语法,有关此方法和所有其他 pm.*
API 方法的更多信息,请参见此处:
https://learning.postman.com/docs/postman/scripts/postman-sandbox-api-reference/
如果您只想注销值而不是将其添加到测试中,您可以在 中使用
选项卡并在 Postman 控制台中看到它显示。console.log(pm.response.json().items.length)
>Tests
关于javascript - 如何计算使用Postman返回的json长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61499647/