我需要创建一定数量的环境变量,这些变量取决于JSON数组中的对象数量。当然,它们的变量需要以不同的名称命名。我尝试了以下但我似乎无法获得创建的变量。
var jsonstuff = JSON.parse(responseBody);
for (var i = 0; i < jsonstuff.bullets.length; i++){
postman.clearEnvironmentVariable("Bullet" + (i+1));
postman.setEnvironmentVariable("Bullet" + (i+1), jsonstuff.bullets[i]);
}
我是Javascript的新手,所以任何信息,无论多么微不足道,都会受到赞赏!
答案 0 :(得分:1)
这里也没有真正的专家,但我总是使用pm.environment.set( "... name ...", jsonData.someProperty);
。我没有尝试过你正在使用的索引。
除此之外,代码中可能存在一些错误,您遗漏了.length
和var
:
for (var i = 0; i < jsonstuff.bullets.length; i++) {
答案 1 :(得分:0)
你的代码对我来说很好......我在我身边嘲笑了一些数据,并且在执行以下操作时工作正常:
var responseBody = {
"bullets": [
{
"_id": "5a32c9b400bf7e499ca242f2",
"index": 0,
"guid": "69ad4f73-b355-4268-94ef-b92f6cab505b",
"picture": "http://placehold.it/32x32"
},
{
"_id": "5a32c9b482a6a89661d98e85",
"index": 1,
"guid": "6c8a1628-3fa9-4b52-b8d3-5719cd3889f7",
"picture": "http://placehold.it/32x32"
},
{
"_id": "5a32c9b4610f9bb923a01a28",
"index": 2,
"guid": "7084aa50-dc85-410c-8dbb-02f860c3d97a",
"picture": "http://placehold.it/32x32"
},
{
"_id": "5a32c9b43c17b09d2e5d819e",
"index": 3,
"guid": "5d076aa8-af3a-4af1-bf49-e62ade7c3ed0",
"picture": "http://placehold.it/32x32"
},
{
"_id": "5a32c9b48594eea1e008c190",
"index": 4,
"guid": "5d1f4bcb-0d59-4acc-af0a-4041a1aefb7f",
"picture": "http://placehold.it/32x32"
}
]
};
//because my example is already an object, it does not need to be parsed into a javascript object
var jsonstuff = responseBody;
for (var i = 0; i < jsonstuff.bullets.length; i++){
postman.clearEnvironmentVariable("Bullet" + (i+1));
//this is the key change. without JSON.stringify(), the environment varible will be set to [Object object]
postman.setEnvironmentVariable("Bullet" + (i+1), JSON.stringify(jsonstuff.bullets[i]));
}
&#13;
注意:没有JSON.stringify,它将环境变量设置为&#34; [对象对象]&#34;