邮递员:如何评估json数组

Joh*_*gel 3 javascript json postman

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

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

[ {
  "id" : "11111111-1111-1111-1111-111111111111",
  "username" : "user-1@example.com",
}, {
  "id" : "22222222-2222-2222-2222-222222222222",
  "username" : "user-2@example.com"
} ]
Run Code Online (Sandbox Code Playgroud)

我添加了一个测试

postman.setGlobalVariable("user_0_id", JSON.parse(responseBody)[0].id);
Run Code Online (Sandbox Code Playgroud)

现在我使用URL向webservice发送连续请求

http://example.com/users/{{user_0_id}}
Run Code Online (Sandbox Code Playgroud)

邮差评估{{user_0_id}}11111111-1111-1111-1111-111111111111.

这很好用.但现在我加入了我的第一次电话测试

postman.setGlobalVariable("users", JSON.parse(responseBody));
Run Code Online (Sandbox Code Playgroud)

在我对webservice的第二次请求中,我调用了URL

http://example.com/users/{{users[0].id}}
Run Code Online (Sandbox Code Playgroud)

但现在{{users[0].id}}无法评估,它保持不变,不会被替换11111111-1111-1111-1111-111111111111.

我能做什么?这个电话的正确语法是什么?

小智 6

要将数组保存在全局/环境变量中,您必须使用JSON.stringify()它.以下是Postman文档中有关环境的摘录:

环境和全局变量将始终存储为字符串.如果你要存储对象/数组,请确保在存储之前使用JSON.stringify(),并在检索时使用JSON.parse().

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

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

postman.setGlobalVariable("users", JSON.stringify(jsonData));
Run Code Online (Sandbox Code Playgroud)

要从全局变量中检索用户的id并在请求URL中使用它,您必须在第二次调用的预请求脚本中解析全局变量,并将值添加到"临时变量"以在其中使用它网址:

postman.setGlobalVariable("temp", JSON.parse(postman.getEnvironmentVariable("users"))[0].id);
Run Code Online (Sandbox Code Playgroud)

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

http://example.com/users/{{temp}}
Run Code Online (Sandbox Code Playgroud)

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

postman.clearGlobalVariable("temp");
Run Code Online (Sandbox Code Playgroud)

这应该为你做的伎俩.据我所知,目前无法直接在URL中解析全局变量来访问特定条目(就像您尝试过的那样{{users[0].id}}).