简体   繁体   English

邮递员(JavaScript)-如何根据JSON数组中的对象数创建环境变量?

[英]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. 我需要创建一定数量的环境变量,这些变量取决于JSON数组中对象的数量。 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! 我是Java语言的新手,所以任何信息,无论多么琐碎,都将不胜感激!

No real expert here either, but I always use pm.environment.set( "... name ...", jsonData.someProperty); 这里也没有真正的专家,但是我总是使用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 : 除此之外,您的代码中可能存在一些错误,您缺少.lengthvar

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]" 注意:如果没有JSON.stringify,它将环境变量设置为“ [Object object]”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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