Post a JSON data to custom table using Scripted REST API
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
02-16-2024 04:17 AM
Hi Everyone,
I have to write scripted rest API to post JSON data to custom table.
Fields in custom table are : sys_id , form_id, u_field1 , u_field2 , u_field3 , u_field4 , u_field5 , etc...
Note : u_field1 and u_field2 are string type whereas u_field3, u_field4and u_field5 are reference type fields.
JSON :
{
"form": {
"formSubmission": {
"formId": "element-lq6p98gw",
"submission": [
{
"type" : "singleLine",
"u_field1" : "TestAsset"
},
{
"type" : "singleLine",
"u_field2" : "1234567890"
},
{"type" : "drowDown",
"u_field3" : "Rack"
},
{
"type" : "dropDown",
"u_field4" : "APC 42U 3100 SP1 NetShelter Rack"
},
{
"type" : "multiLine",
"u_field5" : "example for multiple lines text etc"
}
]
}
}
}
So, requirement is like, I have to compare the fields present on custom table to check wether that field is there on JSON data. If yes then I have to update that field.
Expected result:
Form ID | Field 1 | Field 2 | Field 3 | Field 4 | Field 5 |
element-lq6p98gw | TestAsset | 1234567890 | Rack | APC 42U 3100 SP1 NetShelter Rack | example for multiple lines text |
I have attached Scripted REST API below. Please suggest some method to achieve above requirement.
Thanks in advance
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
02-16-2024 04:19 AM - edited 02-16-2024 05:18 AM
Hi Everyone,
Scripted Rest API :
(function process( /*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
// implement resource here
var requestBody = request.body.dataString;
var parser = new global.JSON();
var parsedData = parser.decode(requestBody);
var formElem = parsedData.form;
var FormID;
var arr_fields = [];
var fields = new GlideRecord('sys_dictionary');
fields.addQuery('name', 'u_customer_details');
fields.addEncodedQuery('internal_type!=collection^ORinternal_type=NULL'); //To ignore all the table dictionaries(optional)
fields.query();
while (fields.next()) {
arr_fields.push(fields.element.toString());
}
gs.info(arr_fields[i]);
var str;
var str1;
if (formElem) {
var FormSubmission = parsedData.form.formSubmission;
if (FormSubmission) {
FormID = parsedData.form.formSubmission.formId;
var Submission = parsedData.form.formSubmission.submission;
for (var t = 0; t < Submission.length; t++) {
var obj1 = Submission[t];
for (key in obj1) {
for (var i = 0; i < arr_fields.length; i++) {
if (key == arr_fields[i]) {
str = obj1[key];
gs.info("str = " +str);
}
}
}
}
var gr = new GlideRecord("u_customer_details");
gr.initialize();
gr.u_formid = FormID;
gr.insert();
}
}
})(request, response);
Please suggest changes to this above code.
cc: @Ankur Bawiskar . Can you suggest some methods please.
Thanks in advance