Clean up my dirty code!

I have a nested Json object and I wanted to get a variable to use in my next test … I got it working but it’s very dirty code, there must be a better way to do this?

Response:
{
“accountSearchResults”: [
{
“userAccount”: {
“userName”: “anyemailgmail.com”,
“ian”: XX2001XXXX,
“firstName”: “John”,
“lastName”: “AdminUser”,
“email”: “anyemailgmail.com”,
“uid”: 152253
},
“secondaryContact”: {
“firstName”: “secondaryContactFN”,
“lastName”: “secondaryContactLN”,
“phone”: “5550020002”
},
“monitoringContact”: {
“addr1”: “2 My Street”,
“addr2”: “Suite 100”,
“city”: “Blue Bell”,
“state”: “PA”,
“csid”: “XXXXX017366”
},
“notificationMethod”: {
“emailOrPhone”: “anyemailgmail.com
}
}
]
}

I was trying to get the “uid”: 152253

My solution was

responseJson = JSON.parse(responseBody);
var list = (responseJson.accountSearchResults[0].userAccount);
var customUid = (list.uid);
//console.log(customUid);
pm.globals.set(“customUid”, customUid);
console.log(pm.globals.get(“customUid”));

on the var list what ever i did then I kept getting error
Is there a cleaner way?

Hi @joncon1967

const response = pm.response.json();
let customUid = response.accountSearchResults[0].userAccount.uid;
pm.globals.set("customUid", customUid);
console.log(customUid);

If you used this global variable in another script you would need to pull it in using;

let myVar = pm.globals.get("customUid");

Just realised how old this post is, but personally I would do a search for the uid which lets you work with whatever element is returned within that object (including the uid itself).

const response = pm.response.json();
pm.test('Search uid', () => {
    let search = (response.accountSearchResults.find(obj => {return obj.uid === '152253'}));
    pm.expect(search).to.have.property('uid');
    pm.expect(search).to.be.an('number');
    console.log(search.uid)
    pm.globals.set(“customUid”, search.uid);
});