From 4b9cf8747ae5649952f57ee3e908faeb1283ac79 Mon Sep 17 00:00:00 2001 From: Ashish Dadhich Date: Tue, 1 Oct 2024 18:31:28 +0530 Subject: [PATCH] Convert a CSV file into object to handle CSV more elegantly Convert a CSV file into object to handle CSV more elegantly to take care of few different scenarios. --- Attachments/CSVParser/script.js | 41 +++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Attachments/CSVParser/script.js diff --git a/Attachments/CSVParser/script.js b/Attachments/CSVParser/script.js new file mode 100644 index 0000000000..c531f937b3 --- /dev/null +++ b/Attachments/CSVParser/script.js @@ -0,0 +1,41 @@ +/********************************************************************************/ +Input: +attachmentQuery - Pass sysId CSV attachment + +Output: +converted into object from CSV + +/********************************************************************************/ + +function parseCSVFile(sysId) { + var attachmentRecord = new GlideRecord("sys_attachment"); + attachmentRecord.get(sysId); + attachmentRecord.query(); + + if (attachmentRecord.next()) { + var stringUtil = new GlideStringUtil(); + var sysAttachment = new GlideSysAttachment(); + var bytesData = sysAttachment.getBytes(attachmentRecord); + var encData = stringUtil.base64Encode(bytesData); + var decData = stringUtil.base64Decode(encData) + ''; + + var delimiter = ','; + var quoteCharacter = '"'; + var csvArray = decData.split("\r\n"); + + var index = 0 + var result = []; + for (index = 0; index < csvArray.length; index++) { + var row = csvArray[index]; + if (row) { + var csvParser = new sn_impex.CSVParser().parseLineToArray(row, delimiter, quoteCharacter); + var rowObject = {}; + for (var i = 0; i < csvParser.length; i++) { + rowObject['column' + (i + 1)] = csvParser[i]; + } + result.push(rowObject); + } + } + return result; + } +} \ No newline at end of file