2017-12-14 4 views
0

JSON 배열에있는 객체의 양에 의존하는 일정량의 환경 변수를 생성해야합니다. 물론 변수의 이름을 다르게 지정해야합니다. 나는 다음과 같은 시도했지만 변수를 만들 수없는 것 같습니다.Postman (JavaScript) - 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]); 
} 

저는 자바 스크립트에 새로운 것이므로 아무리 사소한 정보라도 감사하게 생각합니다!

답변

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

참고 : JSO없이 N.stringify, 환경 변수를 "[Object object]"로 설정했습니다.

+1

대단히 고마워요! 당신이 말했던대로 정확하게 작동했습니다. 미래의 노력을 위해 유의 사항을 명심하십시오. –

+0

굉장! 다행 당신의 방법에있어 :) –

1

여기 실제 전문가는 아니지만 항상 pm.environment.set("... name ...", jsonData.someProperty);을 사용합니다. 사용중인 색인 생성을 시도하지 않았습니다. 그 외에도에서

이 코드에서 몇 가지 오류가있을 수 있습니다, 당신은 .lengthvar 누락 :

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

고마워요! 내가 지적한 오류를 수정했습니다. 다시 달아나지만 여전히 같은 문제가 있습니다. 귀하의 도움을 많이 주시면 감사하겠습니다! –