Parse Text Output to Variable

Can someone help me with following response:

“Session Token-> BAMAuthToken: 4HyQcMTU3MjAwMzA5NTkyMzpnZXIwMDAxcF9hcGk <- for User : ger0001p_api”

I need the token stored in a variable TOKEN. (4HyQcMTU3MjAwMzA5NTkyMzpnZXIwMDAxcF9hcGk)

Thanks and best regards,
Philipp

Hey @ger0001p,

You could give this a go - It’s only going to cover a very basic way of getting and setting that value from the response:

Getting the response body as text using pm.response.text(), splitting the data using the .split() function and then creating an array of those items.

console.log(pm.response.text().split(" "))

The item is 4th in the zero-indexed list so you can reference that using [3] to save that value as an environment variable.

pm.environment.set("TOKEN", pm.response.text().split(" ")[3])

1 Like

Thank you @dannydainton. Works perfect! :slight_smile:

1 Like

You should really encourage the entity responsible for the API to provide you with a parsable response, like JSON. This is really a nasty hack which can easily break in the future.

1 Like

Agreed, This solution will not stand the test of time.

Hi @dannydainton,

Your given solution is working for me but here I have some more text in the next line before the space which one I don’t want to take in my variable value.

So could you please let me know how can I add 2 split in single function or split text.

Response Body:
Job Id : 70c33082-326f-4276-88ca-04dcc046ef55
Total Number of Records: 2
Total Number of Successful Records: 0
Total Number of Failure Records: 2
Total Number of Blank Records: 0

My Script:
var SearchHelp = pm.response.text().split(" ")[3];

Getting ‘SearchHelp’ Value:
70c33082-326f-4276-88ca-04dcc046ef55
Total

and I need only 70c33082-326f-4276-88ca-04dcc046ef55 value in my SearchHelp variable.

Hey @arpit.agrawal,

It seems like you have a different response to the original question and the different pieces of data are on new lines, something like this might help you:

let splitResponse = pm.response.text().split("\n")

pm.environment.set("SearchHelp", splitResponse[0].split(" ")[3])

It looks hacky and it felt hacky even writing this though :frowning_face:

As @vdespa mentioned:

You should really encourage the entity responsible for the API to provide you with a parsable response, like JSON. This is really a nasty hack which can easily break in the future.

1 Like