Create JSON request body through Script
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-20-2023 03:07 AM - edited 11-20-2023 03:22 AM
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.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-21-2023 01:49 AM - edited 11-21-2023 01:50 AM
First of all, I believe you meant
JSON.stringify(current.getValue('description'))
and not
JSON.stringify("" + current.getValue('description'))
The latter variant would make the payload contain the string null - in case description for some reason is empty.
Which would mean the receiving party's description field will end up containing the text null.
In fact I don't think there is a valid use case to ever use
"" + current.getValue('<field name>')
which, b.t.w, is the same as
current.getValue('<field name>').toString()
Also there is a closing parentheses missing in your code.
Other than that you can use GlideRecord.prototype.getValue.
In fact, depending on what the receiving party requires, it would even be better to use it instead of converting the GlideElement into string.
The major difference between current.getValue('description') and current.description.toString() (which is the same as '' + current.description) is what those return when the field is empty.
getValue() returns a null, toString() returns and empty string.
So in case of getValue() the payload will look like:
{
...
"description": null,
...
}
in case of toString() the payload will look like:
{
...
"description": "",
...
}
So if the receiving party understands null or expects/requires null, you can or will have to use getValue().
Otherwise (if the receiving party does not understand and errors on null) you will need to use toString().
An alternative (to toString()) is for you to check in code whether the field is empty or not and issue the appropriate instruction based on that:
if (current.description.nil()) {
request.setStringParameterNoEscape("description", JSON.stringify(""));
}
else {
request.setStringParameterNoEscape("description", JSON.stringify(current.getValue('description')));
}