Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jmbauguess
Last active May 2, 2022 19:24
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jmbauguess/cbc5ad1fedea6d94e13c to your computer and use it in GitHub Desktop.
Save jmbauguess/cbc5ad1fedea6d94e13c to your computer and use it in GitHub Desktop.
Converts a GlideRecord object into JSON, or converts JSON into a GlideRecord. See http://sensibleservicenow.com/?p=49
/**
* @description Converts between JSON Objects and GlideRecords
* @namespace
* @type {Class}
*/
var JSONtoGlide = Class.create();
JSONtoGlide.prototype = {
/**
* @description Converts an object into a new GlideRecord
* @param {Object} json A json object
* @return {GlideRecord} A GlideRecord object
* @example
* var incident = { "_collection_type" : "incident", "short_description" : "Example"};
* var incidentRecord = new JSONtoGlide().marshall(incident);
*/
marshall: function(json) {
if (!this.validateCollectionExists(json._collection_type)) {
gs.log("INVALID COLLECTION : " + json._collection_type, "JSONtoGlide");
return '';
}
var glideRecord = new GlideRecord(json._collection_type),
item;
if (!json.hasOwnProperty('sys_id')) {
glideRecord.initialize();
} else {
glideRecord.get(json.sys_id);
}
for (item in json) {
if (json.hasOwnProperty(item)) {
glideRecord.setValue(item, json[item]);
}
}
if (!json.hasOwnProperty('sys_id')) {
glideRecord.insert();
} else {
glideRecord.update();
}
return glideRecord;
},
/**
* @description Converts a GlideRecord into an object
* @param {GlideRecord} record A GlideRecord
* @return {Object} A json object
* @example
* var incident = new GlideRecord('incident'),
* object;
* if (incident.get('sys_id')) {
* object = new JSONtoGlide().unmarshall(incident);
* }
*/
unmarshall: function(record) {
var fields = new GlideRecordUtil().getFields(record),
resultObject = {},
field;
for (field in fields) {
resultObject[fields[field]] = record.getValue(fields[field]);
}
return resultObject;
},
/**
* @description Ensures a table exists before trying to create a GlideRecord
* @param {String} name The name of the table
* @return {boolean} True if the table exists, false otherwise
* @example
* new JSONtoGlide().validateCollectionExists('incident'); //true
* new JSONtoGlide().validateCollectionExists('fake_table'); //false
*/
validateCollectionExists: function(name) {
var table = new GlideRecord('sys_db_object');
if (table.get('name', name)) {
return true;
}
return false;
},
type: 'JSONtoGlide'
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment