How to convert a gliderecord to JSON?

zsquared
Tera Contributor

Hello,

I am trying to pull a gliderecord from a table and insert it into an JSON object but for some reason my code is not working.

Any ideas?

getRollups();

function getRollups(){

  var myRollUps = [];

  var table = new GlideRecord('random_table');

  table.query();

  while (table.next()) {

  var allocation = 'Applications';

  var percentage = table.u_total_app_cost;

  myRollUps.push({

  'rollupKey': 'name',

  'rollupValue': allocation,

  'rollupAmount': percentage

  });

  }

  return myRollUps;

}

7 REPLIES 7

Nvm~! I got it to work.. I had to convert my field u_total_app_cost to a string~~ by using the .toString() method


Glad you got it to work. Yes, for some fields (data types), conversion using .toString() is necessary; halfway through my blog, I walk through the steps with this explanation: "if not converted, the JSON encoder will treat it as an object, which is not what we want."


sabell2012
Mega Sage
Mega Sage

Zhen:



Awhile back I extended the GlideRecord object.   I added two functions:   toObject, and toObjectList.   My approach handles the problems encountered with directly encoding the GlideRecord object.  



It would be a simple matter to add in the following to produce toJSON:



GlideRecord.prototype.toJSON = function() {


      return new global.JSON().encode(this.toObjectList());


};



The article:   Mini-Lab: Extending the GlideRecord Object  



I also mention a different approach for scoped applications here:   Ask the Expert: Scoped Libraries with Steve Bell



Steven.