Setting postman environment variable from within script tags

Within my current visualizations I make heavy use of postman variables within the tests and pass this detail to functions:

 <div id="container" class="container">
<table id = "${pm.info.requestId}" table class="row-border" style="width:100%">

This allows me to use postmans unique idā€™s in running my scripts and keeps my charts / tables / etc running smoothly.

Now though - I have a use case where I need to go the other way and store something that my js creates to an environment variable from with script tags.

                    var json_object = JSON.stringify(XL_row_object);
                      document.getElementById("jsonObject").innerHTML = json_object;

This code creates the following html detail:

And now I want to preserve that detail in an environment variable. Iā€™ve tried all the following to no success:

${pm.environment.set(ā€œtradesā€, jsonObject};
${pm.environment.set(ā€œtradesā€, ā€˜#jsonObjectā€™)};
${pm.environment.set(ā€œtradesā€, } + #json_Object);

Hey,

Why donā€™t you start with something basic and see if it works:

${pm.environment.set('foo', 'bar')}

I am not sure I understand the syntax that you have there.

It doesnā€™t. As said - Iā€™m in a script tag. When I do the above - it sets it to the value of jsonObject as a string - which is then represented at jsonObject - instead of the content of the jsonObject tag in the script.

Instead of the content of the jsonObject variable which is:

]

here is my code:

<script>
    $(document).ready(function(){
          $("#fileUploader").change(function(evt){
                var selectedFile = evt.target.files[0];
                var reader = new FileReader();
                reader.onload = function(event) {
                  var data = event.target.result;
                  var workbook = XLSX.read(data, {
                      type: 'binary'
                  });
                  workbook.SheetNames.forEach(function(sheetName) {
                      var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
                      var json_object = JSON.stringify(XL_row_object);
                      document.getElementById("jsonObject").innerHTML = json_object;
                      ${pm.environment.set('trades', 'json_Object')};
                    })
                };
                reader.onerror = function(event) {
                  console.error("File could not be read! Code " + event.target.error.code);
                };
                reader.readAsBinaryString(selectedFile);
          });
         
         
    });
</script>

Once in a script - Iā€™m flummuxed as to how to send script variables back to postman. It is easy to send postman variables into the script - but none of the methods Iā€™ve tried seem to work.

As you see - the var = json_object has been initialized with the jsonObject. I now want to write eiher jsonObject - or the content of the var to an environment variable.

I am no expert, I am just stating my opinion/observation.

It seems that you donā€™t have access to the entire scope of the pm.* object from scripts.

Only pm.getData() and pm.getResponse() are available. The rest is a typical JavaScript window object.

Anything that gets evaluated inside the template with ${foo} runs in the normal ā€œTestsā€ context and has access to everything.

So the script block that you put in the template and the template run in two different JavaScript contexts that donā€™t share any data.

Why do you need to write data from a template/script? Canā€™t you just write a ā€œnormalā€ script within the ā€œTestsā€?

Also this syntax ${pm.environment.set(ā€˜tradesā€™, ā€˜json_Objectā€™)} is not needed in the way you have used it.

The script itself initiates the load of an excel sheet - converts it to json - and writes the excel content in json to the visualizer window. I now want to grab that data (the converted excel) and use it in a subsequent api call. so - I need to be able to pass the contents of what the js has done to an environment variable to persist it for future calls.

Thanks for looking at this with me btw. I could be going about it wrong - but Iā€™m using multiple script libraries that are set to script src above. I do get the response I want in the response window on the visualizer. And I have to use visualizer becuase the user initiates the file upload with a button. Once they do - the excel sheet is parsed to Json and displayed in the response window. If I can set it to a variable - I can use that response in a subsequent post.

So where I am now:
Visualizer works - user clicks button - loads excel sheet from computer
Script is converting the xlsx format nicely to json
Json from the spreadsheet is showing in the visualizer window

Where Iā€™m stuck - is persisting that json data into an environment variable to be used by another call.

Iā€™m doing this the other way - passing environment variables to other script libraries such as autotable, jspdf, datatables - and use them extensively - especially the responseId because this keeps all my tables as having unique names that are the invoked in functions. Here is the result of that work. And the reason was - I can reuse the code and only change the handlebars without worrying about changing table ids or anything else in the scripts!

Heck - I even tried putting all of my var template ā€™ into an environment variable and just calling it - which would have given me a single place to change scripts affecting hundreds of calls - but that didnā€™t work. Idea was - just have either lodash or handlebars in the test window - and leave all the js and jquery elsewhereā€¦

Another option is I could just write a function to post directly once the file has been uploaded - but then I miss out on the error messaging postman supplies I thinkā€¦ but that is for tommorow.

Part of the issue is that you are using the Visualizer in a way that it has not been designed.

Sounds exactly like what my mother said when I told her I liked boys! Lol. That said- its working - so effectively I have an API to excel that grabs excel data, reformats it to json, posts it to a webapi, and visualizes the sheet, the json, and the result. Iā€™m really happy

1 Like