How to solve error when fetching json response using regex?

i want to retrieve the value “id” from the following json response:
[
{
“id”: 134755304,
“from”: “postmaster@email.ncloud.com”,
“subject”: “Verify your email address to complete your Account registration.”,
“date”: “2023-01-20 22:28:12”
}
]

I use RegEx to get the “id” value, but it doesn’t work.
the following is the code in my postman test:

const res = pm. response. json();
let body = res.x[0].id;
const regex = /\d{9}/gm;

console. log(regex. exec);
pm.environment.set(“idemail”, regex.exec(x[0].id));

but i used the above code got an error like this,
TypeError: Cannot read properties of undefined (reading ‘0’)

please help me solve this

Why are you using RegEx?

Your response is an array with 1 element in it.

Therefore you have two ways of getting to the ID element.

  1. You can parse the response directly to the first element.
  2. You target the first element after parsing.
response = pm.response.json()[0]; // arrays start at zero
console.log(response.id);

// or 

response = pm.response.json();
console.log(response[0].id);

I’m not sure where your the “x” is coming from in your code. Not really sure what you are trying to do with the RegEx either.

TypeError: Cannot read properties of undefined (reading ‘id’)

when running collection, I get the above error

Your not giving us much to go on.

Does it work when running it individually outside of the collection runner? Or does it fail then as well?

Can you confirm that the response is exactly as how you posted it. A single array with a single object in it?

The console log shows all requests\responses. Including the ones sent during a collection run. Check those request\responses, and ensure that they are running ok, that they are all returning 200 ok and that the body of the response matches your example. (Or ideally create tests in your code to check the status code). If the response is not coming back properly for some reason, then it won’t be able to find the ID, and can cause the error you are reporting.

Break down the console logs. Parse the response using pm.response.json() and then console log the response. Then define the ID and console log that separately. It’s easier that way to see when things are going wrong.