邮递员:如何评估 json 数组

Postman: how to evaluate json arrays

使用 Postman 可以将响应主体中的特殊字段保存到变量中,并在连续调用中使用该变量的值。

例如: 在我第一次调用网络服务时,响应正文中返回以下内容

[ {
  "id" : "11111111-1111-1111-1111-111111111111",
  "username" : "user-1@example.com",
}, {
  "id" : "22222222-2222-2222-2222-222222222222",
  "username" : "user-2@example.com"
} ]

我添加了测试

postman.setGlobalVariable("user_0_id", JSON.parse(responseBody)[0].id);

现在我使用 URL

向网络服务发送一个连续的请求
http://example.com/users/{{user_0_id}}

邮递员将 {{user_0_id}} 计算为 11111111-1111-1111-1111-111111111111

这很好用。但是现在我添加到我的第一个电话的测试中

postman.setGlobalVariable("users", JSON.parse(responseBody));

在我对网络服务的第二次请求中,我调用了 URL

http://example.com/users/{{users[0].id}}

但现在{{users[0].id}}无法计算,它保持不变,没有被11111111-1111-1111-1111-111111111111取代。

我能做什么?调用的正确语法是什么?

要将数组保存在 global/environment 变量中,您必须 JSON.stringify() 它。这是 Postman documentation about environments 的摘录:

Environment and global variables will always be stored as strings. If you're storing objects/arrays, be sure to JSON.stringify() them before storing, and JSON.parse() them while retrieving.

如果确实有必要保存整个响应,请在第一次调用的测试中执行如下操作:

var jsonData = JSON.parse(responseBody);
// test jsonData here

postman.setGlobalVariable("users", JSON.stringify(jsonData));

要从全局变量中检索用户 ID 并在请求中使用它 URL,您必须在第二次调用的预请求脚本中解析全局变量并将值添加到a "temporary variable" 在 URL:

中使用它
postman.setGlobalVariable("temp", JSON.parse(postman.getEnvironmentVariable("users"))[0].id);

因此,第二个调用的 URL 将是:

http://example.com/users/{{temp}}

在第二次调用的测试中,确保在最后清除临时变量:

postman.clearGlobalVariable("temp");

这应该可以解决您的问题。据我所知,目前无法直接在 URL 中解析全局变量以访问特定条目(就像您尝试对 {{users[0].id}} 所做的那样)。