简体   繁体   中英

Postman (JavaScript) - How do I create environment variables based on how many objects are in a JSON array?

I need to create a certain amount of environment variables that depend on the amount of objects in a JSON array. They variables need to be named differently, of course. I've tried the following but I can't seem to get the variables created.

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]);
}

I'm brand new to Javascript, so any information, no matter how trivial, will be appreciated!

No real expert here either, but I always use pm.environment.set( "... name ...", jsonData.someProperty); . I have not tried the indexing that you are using.

Apart from that, there may be some errors in your code, you are missing .length and var :

for (var i = 0; i < jsonstuff.bullets.length; i++) {

Your code looks good to me... I mocked some data on my side and it worked fine when doing the following:

 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])); } 

NOTE: Without JSON.stringify, it was setting the environment vars to "[Object object]"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM