Create JSON request body through Script

RFJ1
Tera Contributor

Hi,

 

I want to create JSON request body through script. Can someone help me with the code?

 

var request = new sn_ws.RESTMessageV2('User Group', 'Group Updation');
request.setStringParameter('sysid' , "a69fc6a21b227dd8df7132e2cd4bcb91");
for (var x in current)
{
 if(current[x] != previous[x])
 request.setRequestBody('{"'x'" : "'+ current.[x]'"}');
}

 

I want to loop through each field and if the value of any field is different, i want to add that field name and its current value to the request body. If the values are hardcoded string we can use '\' character but how can we pass variable names and its value in the request body.

 

Thanks in advance. 

15 REPLIES 15

Anand Kumar P
Giga Patron
Giga Patron

Hi @RFJ1 ,

Try below script push value into object and then stringify that and then set it to request body.

var request = new sn_ws.RESTMessageV2('User Group', 'Group Updation');
request.setStringParameter('sysid', "a69fc6a21b227dd8df7132e2cd4bcb91");
var requestBody = {}; 
for (var x in current) {
    if (current[x] != previous[x]) {
        requestBody[x] = current[x];
    }
}
var requestBodyString = JSON.stringify(requestBody);
request.setRequestBody(requestBodyString);

Check if there are any BR's or any client scripts that is clearing the short description.

 

Thanks,

Anand


 

Hi @Anand Kumar P 

 

I tried the script and got the below as output, the field names are added but the values are not coming.

This was the result I got,

Rest Group Updation :{"sys_updated_on":{},"email":{},"sys_mod_count":{},"name":{}}

 So I made a small change,

 requestBody[x] = current.getValue(x);

and got the result that i wanted,

Rest Group Updation :{"sys_updated_on":"2023-11-20 12:03:33","email":"xyz12345@example.com","sys_mod_count":"4","name":"Test from REST 2567"}

 

RFJ1
Tera Contributor

Thank you for helping

Here's an article explaining the problem you encountered (but then fixed): TNT: The Importance of Using "getValue()" when Getting Data from a GlideRecord