Get and set value from json response does not store the content of the value

Hi,
with request GET i get a response and ièm trying to set a data from the response as global variable.
i tried this:
var responseJson = pm.response.json();

pm.globals.set(‘idReques’, (responseJson.idRequest[0]).toString());
returns: TypeError: Cannot read property ‘0’ of undefined

pm.globals.set(‘idReques’, (responseJson.idRequest).toString());
returns: There was an error in evaluating the test script: JSONError: Unexpected token ‘<’ at 1:1 ^

Hello @ps198478320, I have moved in your topic to “Help” category to get better attention as this will the correct category for such queries :blush:

And coming to your question, the element which you are trying to access is invalid. Can you try viewing it in console?

responseJson.idRequest[0]
responseJson.idRequest

Possible share some screenshots please, or the response if it’s allowed to share :slightly_smiling_face:

1 Like

Hi,
i can t share screenshot.
but here is what iè m doing:

var responseJson = pm.response.json();
pm.globals.set(‘idReques’, (responseJson.idRequest));

there is no error but the value of idRequest is empty when i check global variable:
i can see it created the variable idRequest but its value is empty.

The json response starts like this:

[

{

    "idRequest": "bf9b72ae-6eaf-41c0-94ff-21a0e78c78a3",

    "idWorkflow": "a3f544fe-7466-4597-9e0d-9c8475a16249",

Hi @ps198478320,

That response sample is very helpful I think :slight_smile: The initial square bracket indicates that the response is actually inside an array, so you need to indicate that you want to read the values from within the first item of the array -

var responseJson = pm.response.json();
pm.globals.set('idReques', (responseJson[0].idRequest));

Here is a quick example I made, using a variable with the same structure as your response, which demonstrates this:

var sampleResponse = [{"idRequest":"my-request-id", "idWorkflow": "my-workflow-id"}];
console.log(sampleResponse.idRequest); // outputs "undefined"
console.log(sampleResponse[0].idRequest); // outputs "my-request-id"
1 Like

It works thank you.
I was trying with this which is not correct.
pm.globals.set(‘idReques’, (responseJson.idRequest[0]));

1 Like