retrieve field from response.getBody()

Amol J
Kilo Contributor

Hi,

I am setting the data in following way

user.push({
'role':roles
});

 

and receiving it through REST api 

var response = request.execute();

var res = response.getBody();

it is giving me complete object see below

find_real_file.png

I want to get roles from this array How can I achieve this?

6 REPLIES 6

Harsh Vardhan
Giga Patron

try now. also add sample json value if below code does not work. 

 

var res = response.getBody();

var op = JSON.parse(res);

 

gs.log('Value is '+ op.role.length);

for(var i = 0 ; i< op.role.length;i++){

gs.log('Result is '+ op.role[i]);

}

Harsh Vardhan
Giga Patron

here is the updated script. i created sample json same like you have to fetch the role value.  you can use the same logic. 

 

var res = {
"result":[
{
"role":[
"abc",
"def",
"ghs"
]
}
]
}

var op = JSON.stringify(res);

var ot = JSON.parse(op);
for(var i = 0 ; i< ot.result.length;i++){


gs.log('Value is '+ot.result[i].role);

}

Harsh Vardhan
Giga Patron

in your case it would be like below code. give a try and let me know the logs if it does not work.

 

var response = request.execute();

var res = response.getBody();

 

var ot = JSON.parse(res);
for(var i = 0 ; i< ot.result.length;i++){


gs.log('Value is '+ot.result[i].role);

}

 

If it helps you, mark the answer correct and helpful.

Actually I am not getting any value in the log 

 

see my code 

 

setting:-

 

  if (gr.next()) {
var gr1=new GlideRecord('sys_user_has_role');
gr1.addQuery('user',gr.sys_id);
gr1.query();
while(gr1.next()){


roles.push(gr1.getDisplayValue('role'));

}

user.push({
'role':roles
});
 

return user;

 

getting:-

 

var response = request.execute();


var res = response.getBody();
var op = JSON.stringify(res);

var ot = JSON.parse(op);
for(var i = 0 ; i< ot.result.length;i++){


gs.addInfoMessage('Value is '+ot.result[i].role);

}